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

用 HttpURLConnection 實作帶參數的檔案上傳

編輯:關於 Android 程式設計

檔案上傳是常見需求。網路上多數範例採用 HttpClient 並額外引入 httpmime.jar,其實光靠 HttpURLConnection 也能完成,不必多一層相依。不過要先說清楚它的限制:在行動端它不太適合上傳大檔案,比較適合處理體積不大的圖片或小型附件。

先搞懂 multipart/form-data 的格式

要帶參數上傳檔案,就必須自己動手組出請求本文。HttpURLConnection 不會幫你拼 multipart 主體,所以理解 HTTP 請求的構造方式是前提。以下是一個典型的請求樣貌:

POST /api/feed/ HTTP/1.1
Accept-Encoding: gzip
Content-Length: 225873
Content-Type: multipart/form-data; boundary=OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Host: www.myhost.com
Connection: Keep-Alive

--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Content-Disposition: form-data; name=param1
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

888
--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Content-Disposition: form-data; name=param2
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

nihao
--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Content-Disposition: form-data; name=images; filename=/storage/emulated/0/Camera/jdimage/1xh0e3yyfmpr2e35tdowbavrx.jpg
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary

這裡是圖片的二進制資料
--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp--

請求標頭逐行解讀

第一行:POST 方法,請求路徑為 /api/feed/。若伺服器是 www.myhost.com,完整網址即為 www.myhost.com/api/feed/,最後標明 HTTP 協議版本 1.1。

第二行:可接受壓縮方式。

第三行:本文長度。

第四行:Content-Type 指定為 multipart/form-data,代表以表單方式上傳。boundary 是必須指定的分隔符,不同參數之間靠它區隔,這串字串可以自行隨機產生。

第五行:主機位址。

第六行:Keep-Alive 持久連線,避免反覆建立與重建連線。

第七行:空行,用來結束標頭區。這個換行是必須的。

參數區逐行解讀

--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Content-Disposition: form-data; name=param1
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

888

第一行:以分隔符宣告一個參數開始,注意分隔符前面還要加上兩個減號,這也是必須的。

第二行:name=param1,param1 就是參數的鍵名,等同於 GET 方式中的 https://www.baidu.com?param1=888。

第三行:內容格式為 text/plain,並指定編碼 charset=UTF-8。

第四行:Content-Transfer-Encoding 描述實體的傳輸形式,純文字設為 8bit,檔案則設為 binary。

第五行:空行,必須。

第六行:參數值,此例為 888。

後續的 param2 同理。到了檔案參數,格式相同,只是 Content-Disposition 多帶一個 filename,Content-Type 換成 application/octet-stream,編碼改為 binary,空行之後直接寫入二進位內容,最後以「分隔符 + 兩個減號」收尾。

這裡一個字都不能出錯——格式不對,上傳就會失敗。

封裝成上傳工具類

/**
 * 帶參數的檔案上傳工具
 */
public class FileUploader {

    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 10000000;
    private static final String CHARSET = "utf-8";

    public static void upload(String host, File file, Map<String, String> params,
                              FileUploadListener listener) {
        String BOUNDARY = UUID.randomUUID().toString();
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data";

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

            if (file != null) {
                OutputStream outputSteam = conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(LINE_END);

                // 拼接文字參數
                if (params != null) {
                    for (Map.Entry<String, String> entry : params.entrySet()) {
                        sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                        sb.append("Content-Disposition: form-data; name=\"")
                          .append(entry.getKey()).append("\"").append(LINE_END);
                        sb.append("Content-Type: text/plain; charset=").append(CHARSET).append(LINE_END);
                        sb.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
                        sb.append(LINE_END);
                        sb.append(entry.getValue());
                        sb.append(LINE_END);
                    }
                }

                // 拼接檔案參數
                sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                // name 對應伺服器端接收檔案的欄位名稱
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"")
                  .append(file.getName()).append("\"").append(LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=")
                  .append(CHARSET).append(LINE_END);
                sb.append(LINE_END);

                dos.write(sb.toString().getBytes());

                // 寫入檔案內容並回報進度
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                long totalbytes = file.length();
                long curbytes = 0;
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    curbytes += len;
                    dos.write(bytes, 0, len);
                    listener.onProgress(curbytes, 1.0d * curbytes / totalbytes);
                }
                is.close();

                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();

                int code = conn.getResponseCode();
                sb.setLength(0);
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                listener.onFinish(code, sb.toString(), conn.getHeaderFields());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public interface FileUploadListener {
        void onProgress(long pro, double precent);
        void onFinish(int code, String res, Map<String, List<String>> headers);
    }
}

呼叫方式

public class MainActivity extends FragmentActivity {

    File sdDir;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        }

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("aa", "bb");

        new Thread() {
            @Override
            public void run() {
                FileUploader.upload("上傳位址",
                        new File(sdDir.getPath() + "/檔案名"), map,
                        new FileUploader.FileUploadListener() {
                    @Override
                    public void onProgress(long pro, double precent) {
                        Log.i("cky", precent + "");
                    }

                    @Override
                    public void onFinish(int code, String res,
                                         Map<String, List<String>> headers) {
                        Log.i("cky", res);
                    }
                });
            }
        }.start();
    }
}

幾點實務提醒

網路操作一定要放在子執行緒,主線程做這件事會直接觸發 NetworkOnMainThreadException。另外若要上傳到 Android 10 以上的裝置,直接存取 Environment.getExternalStorageDirectory() 已受限制,需改用儲存空間存取架構或自身應用目錄。這套寫法在當年很好用,如今若無特殊理由,建議優先考慮成熟的上傳框架。

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