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

Android 上傳檔案到伺服器:HttpURLConnection 搭配 multipart/form-data 實作

編輯:關於 Android 程式設計

行動裝置產生的資料越來越多,照片、語音、日誌檔往往都需要回傳到後端。在 Android 上最不需要額外相依套件的上傳方式,就是直接利用 HttpURLConnection 手動組出 multipart/form-data 的請求本文。這篇文章把整個流程拆開來講,讓你明白每一段位元組到底在做什麼。

為什麼要用 multipart/form-data

表單上傳本質上是把「文字欄位」與「檔案內容」拼在同一個請求本文裡,再用一段絕不會出現在資料中的字串作為分隔界標,也就是 boundary。伺服器收到後依序切開,就能分別取得欄位值與檔案位元組。界標通常用 UUID 隨機產生,避免碰撞。

完整程式碼

public class PostFile {
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 1000;   // 逾時時間
    private static final String CHARSET = "utf-8";  // 編碼

    /**
     * 上傳檔案到伺服器
     * @param file      要上傳的檔案
     * @param params    附帶的表單欄位
     * @param RequestURL 請求網址
     * @return 伺服器回應內容
     */
    public static String uploadFile(File file, Map<String, String> params, String RequestURL) {
        String result = null;
        String BOUNDARY = UUID.randomUUID().toString(); // 隨機邊界標識
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data";

        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Charset", CHARSET);
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

            if (file != null) {
                // 1. 先寫入檔案本體
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();

                // 2. 組出表單欄位
                StringBuilder sbs = new StringBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    sbs.append(PREFIX).append(BOUNDARY).append(LINE_END);
                    sbs.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"")
                       .append(LINE_END).append(LINE_END);
                    sbs.append(entry.getValue()).append(LINE_END);
                }
                sbs.append(PREFIX).append(BOUNDARY).append(LINE_END);
                sbs.append("Content-Disposition: form-data; name=\"filelength\"")
                   .append(LINE_END).append(LINE_END);
                sbs.append(file.length()).append(LINE_END);

                dos.write(sbs.toString().getBytes());
                dos.write(LINE_END.getBytes());

                // 3. 收尾邊界
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();

                // 4. 讀取回應,200 代表成功
                int res = conn.getResponseCode();
                Log.i(TAG, "response code:" + res);
                if (res == 200) {
                    InputStream input = conn.getInputStream();
                    byte[] bs = new byte[input.available()];
                    input.read(bs);
                    result = new String(bs, "GBK");
                    Log.i(TAG, "result : " + result);
                } else {
                    Log.i(TAG, "request error");
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

幾個實務上要注意的細節

  • 逾時設定:大檔上傳容易超過預設逾時,10 秒對小檔案夠用,影音檔建議調到 30 秒以上。
  • 編碼一致性:請求標頭用 UTF-8,回應卻用 GBK 解碼並不妥當,正式專案應統一為 UTF-8。
  • 不要寫在 UI 執行緒:網路 I/O 在 Android 4.0 之後會直接拋出 NetworkOnMainThreadException,請搭配 AsyncTask、Thread 或 Kotlin 協程。
  • 串流要關閉:InputStream、DataOutputStream 建議改用 try-with-resources 或 finally 收尾,避免連線洩漏。
  • 權限別忘了:需在 AndroidManifest.xml 加入 android.permission.INTERNET。

更現代的替代方案

如果只是專案內部使用,OkHttp 的 MultipartBody 與 Retrofit 能把上面幾十行收斂成幾行宣告,並自動處理重試、連線池與串流上傳。手寫版本的好處是零相依、可控性高,適合需要微調封包的場景;兩者取決於你的專案規模與維護成本考量。

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