編輯:關於 Android 程式設計
最近在做文件上傳的服務,看了不少教程,多數只講客戶端、不給服務端,可沒有服務端根本沒法調試。所以這裡兩邊都給。
客戶端核心很簡單:HttpURLConnection 加上一個 ProgressBar。
繼承 AsyncTask,在 doInBackground 裡分塊讀文件並寫入輸出流,每寫一塊就用 publishProgress 回報一次百分比。
private ProgressBar mPgBar;
class UploadTask extends AsyncTask<Object, Integer, Void> {
private DataOutputStream outputStream = null;
private String fileName;
private String uri;
private String mLineEnd = "\r\n";
private String mTwoHyphens = "--";
private String boundary = "*****";
File uploadFile;
long mTtotalSize;
public UploadTask(String fileName, String uri) {
this.fileName = fileName;
this.uri = uri;
uploadFile = new File(fileName);
mTtotalSize = uploadFile.length();
}
@Override
protected Void doInBackground(Object... objects) {
long length = 0;
int mBytesRead, mbytesAvailable, mBufferSize;
byte[] buffer;
int maxBufferSize = 256 * 1024; // 每塊 256KB
try {
FileInputStream fileInputStream = new FileInputStream(new File(fileName));
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 如有需要可在此附加 Cookie
// con.setRequestProperty("Cookie", "JSESSIONID=" + cookie);
con.setChunkedStreamingMode(256 * 1024); // 分塊傳輸,避免一次性緩存整個文件
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(con.getOutputStream());
// 拼接 multipart 協議的頭部
outputStream.writeBytes(mTwoHyphens + boundary + mLineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ fileName + "\"" + mLineEnd);
outputStream.writeBytes("Content-Type:application/octet-stream \r\n");
outputStream.writeBytes(mLineEnd);
mbytesAvailable = fileInputStream.available();
mBufferSize = Math.min(mbytesAvailable, maxBufferSize);
buffer = new byte[mBufferSize];
mBytesRead = fileInputStream.read(buffer, 0, mBufferSize);
while (mBytesRead > 0) {
outputStream.write(buffer, 0, mBufferSize);
length += mBufferSize;
publishProgress((int) ((length * 100) / mTtotalSize)); // 回報進度
mbytesAvailable = fileInputStream.available();
mBufferSize = Math.min(mbytesAvailable, maxBufferSize);
mBytesRead = fileInputStream.read(buffer, 0, mBufferSize);
}
// 補上 multipart 結尾
outputStream.writeBytes(mLineEnd);
outputStream.writeBytes(mTwoHyphens + boundary + mTwoHyphens + mLineEnd);
publishProgress(100);
int serverResponseCode = con.getResponseCode();
String serverResponseMessage = con.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
Log.v(TAG, "uploadError");
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
mPgBar.setProgress(progress[0]);
}
}
有個地方容易踩坑:
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"" + mLineEnd);
name 的值必須和服務端約定的參數名一致。我的服務端把文件參數命名為 file,這裡就寫 file;如果你們後端約定的是 upload 或 avatar,記得同步改,否則兩邊永遠對不上。
服務端用 Struts2 接收,先把上傳相關屬性封裝好。這裡定義成 List,天然支持多文件上傳。
// 上傳文件集合
private List<File> file;
// 文件名集合
private List<String> fileFileName;
// 內容類型集合
private List<String> fileContentType;
public List<File> getFile() { return file; }
public void setFile(List<File> file) { this.file = file; }
public List<String> getFileFileName() { return fileFileName; }
public void setFileFileName(List<String> fileFileName) { this.fileFileName = fileFileName; }
public List<String> getFileContentType() { return fileContentType; }
public void setFileContentType(List<String> fileContentType) { this.fileContentType = fileContentType; }
測試用的 Action:
public String testUpload() throws Exception {
System.out.println("success");
uploadFile(0); // 只上傳了一個文件,取下標 0
return SUCCESS;
}
真正的落盤邏輯——把框架緩存在臨時目錄的文件搬到目標目錄,並用 UUID 拼接原文件名避免重名:
/**
* 上傳功能
*/
private String uploadFile(int i) throws FileNotFoundException, IOException {
try {
InputStream in = new FileInputStream(file.get(i));
String dir = "D://UploadData/";
File uploadFile = new File(dir, StringUtils.getUUID() + getFile(this.getFileFileName().get(i)));
OutputStream out = new FileOutputStream(uploadFile);
byte[] buffer = new byte[1024 * 1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
return uploadFile.getAbsolutePath();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
<!-- 上傳文件字符集編碼 --> <constant name="struts.i18n.encoding" value="utf-8"></constant> <!-- 上傳文件臨時存放路徑 --> <constant name="struts.multipart.saveDir" value="c:\tmp\"></constant> <!-- 上傳大小上限 --> <constant name="struts.multipart.maxSize" value="10000000" />
這裡主要定義臨時目錄和大小限制,實際專案按需求調整即可。
效果圖:

最後補充一點:AsyncTask 早已被官方標記為不推薦,真實專案中建議改用 OkHttp 的異步上傳或 WorkManager,配合自定義的 ProgressListener 回報進度,同時也能更好地處理弱網重試與斷點續傳。
Android Permission權限與安全機制解析(下)
Android 6.0權限全面詳細分析和解決方案 Marshmallow版本的權限變更 Android的權限系統一直是最重要的安全概念之一,但這些權限過去只在安裝時被詢問
Android WebView 使用大全:loadUrl、loadData 與 JavaScript 雙向通信
WebView 是 Android 提供的網頁瀏覽元件,能載入遠端網頁,也能渲染本地 HTML。它本質上是一個完整的瀏覽器引擎,理解這一點,很多進階玩法就顺理成章了。以下
Eclipse Android 專案 XML 檔案格式化配置教程
收尾,這樣可讀性才高。 要達到這樣的格式化效果,需要修改 Eclipse 的一些設定,並做一點額外操作。 一、修改 XML 格式化設定 這一步的目的是讓每個屬性配置各
Android 建立與解析 XML(三)——Sax 方式詳解
1. Sax 概述SAX 是一種占用記憶體少、解析速度快的解析器。它採用「事件啟動」的機制,不需要一次解析整個文件,而是依內容順序逐段檢視是否符合 xml 語法,若符合就