Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 上傳文件到服務端並實時顯示進度

編輯:關於 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;
}

三、Struts2 配置

<!-- 上傳文件字符集編碼 -->
<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 回報進度,同時也能更好地處理弱網重試與斷點續傳。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved