在瀏覽器環境裡上傳檔案,HTTP 是最直覺的選擇,但當檔案稍大時,一次傳完的風險也跟著升高——網路一斷就得從頭再來。下面這份 Applet 範例的解法是先向伺服器問一句「這個檔案已經收到多少位元組」,再從那個位置續傳剩下的部分。
整個流程可以拆成三段:getConnection() 建立並設定 HttpURLConnection;getServletObject() 送出一個簡單的請求、讀回伺服器回報的已接收位元組數;若尚未傳完,sendServletObject() 就把剩餘內容以串流寫出去。
package com.cxsoft.applet;
import java.applet.Applet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/****************************************
* <p>Title:UploadFile </p> *
* <p>Description:上傳檔案的 applet </p> *
* <p>@author jerry </p> *
* <p>version: 1.0 </p> *
****************************************/
public class UploadFile extends Applet {
private static final long serialVersionUID = 1L;
public UploadFile() throws Exception {
HttpURLConnection con = this.getConnection();
con.disconnect();
//處理本地需要上傳的檔案
String path = "D:\\EdmsScanDemo\\tm.zip";
File file = new File(path);
long fileLength = file.length(); // 取得檔案位元組數
System.out.println("要上傳的檔案大小為:" + fileLength);
//上傳檔案到伺服器
long startPos = this.getServletObject(con); //取得伺服器的回傳資訊
//判斷是否需要上傳
if(startPos < fileLength) {
System.err.println("檔案未傳完,現在開始上傳剩餘部分");
this.sendServletObject(con, path, startPos);
} else {
System.err.println("該檔案已存在!");
}
}
/****************************************
* <p>功能:上傳檔案到伺服器 </p> *
* <p>@param con 與伺服器的連接 </p> *
* <p>@param path 需要上傳的檔案的路徑 </p> *
* <p>@throws IOException </p> *
****************************************/
private void sendServletObject(HttpURLConnection con, String path, long nstartPos)
throws Exception {
FileInputStream fis = null;
BufferedInputStream bis = null;
con = this.getConnection();
long startPos = nstartPos; //開始上傳的位置
BufferedOutputStream bos = null;
byte[] buf = new byte[4096]; //定義一個緩衝區
int len = 0;
try {
bos = new BufferedOutputStream(con.getOutputStream());
fis = new FileInputStream(path);
bis = new BufferedInputStream(fis);
bis.skip(startPos);
while ((len = bis.read(buf)) != -1) {
bos.write(buf, 0, len); //上傳檔案
bos.flush(); //緩衝刷新
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
if (fis != null) {
fis.close();
}
if (bos != null) {
bos.flush();
bos.close();
}
buf = null;
}
}
/********************************
* <p>功能:取得與伺服器的連接 </p> *
* <p>@return </p> * <p>@throws Exception </p> *
********************************/
private HttpURLConnection getConnection() throws Exception{
String url = "https://localhost:8080/UploadTest/temp";
String data = "test.zip";
URL server = new URL(url + "?filename=" + data);
HttpURLConnection con = (HttpURLConnection) server.openConnection(); //取得伺服器端連接
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setDefaultUseCaches(false);
return con;
}
/********************************************
* <p>Title:getServletObject </p> *
* <p>Description:取得伺服器端的回傳資訊 </p> *
* <p>@param con </p> *
* <p>@throws IOException </p> *
********************************************/
private long getServletObject(HttpURLConnection con) throws Exception {
//向伺服器端發送請求
ObjectOutputStream os = new ObjectOutputStream(con.getOutputStream());
os.write(1);
os.close();
//取得伺服器端的回傳資訊
ObjectInputStream ins = new ObjectInputStream(con.getInputStream());
String nStartPos = ins.readUTF();
System.out.println("已上傳的位元組數為:" + nStartPos);
ins.close();
return Long.parseLong(nStartPos);
}
public static void main(String[] args) {
try {
UploadFile up = new UploadFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
續傳的關鍵在 bis.skip(startPos):先把讀取指針移到伺服器已收到的位置,後續的迴圈自然只會送出缺少的尾巴。伺服器端則需要一個對應的接口,能回報目前檔案大小,並以 append 模式接收資料。
另外提醒,範例中的註解寫「4M 緩衝區」,實際配置是 4096 位元組也就是 4KB,兩者差了三百倍,照抄時別被註解誤導。若換成更現代的寫法,HttpURLConnection 可以改用 setFixedLengthStreamingMode() 或 setChunkedStreamingMode(),避免整個檔案被先緩衝進記憶體;而 Applet 本身已屬夕陽技術,新專案更值得考慮改用 HTML5 的表單上傳或 fetch 搭配串流。