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

Golang + Android:以 HttpURLConnection 實作檔案上傳

編輯:關於 Android 程式設計

本文示範一組最經典的搭配:Android 端作為用戶端,用 HttpURLConnection 發送 multipart 請求;Golang 端作為伺服器,接收並落地存檔。整個流程不依賴任何第三方套件。

用戶端:手工組裝 multipart 資料

上傳檔案的關鍵在於三件事:請求方法必須是 POST、Content-Type 要指定 multipart/form-data 並帶上 boundary 分隔符、以及請求本文必須嚴格按照「分隔符 → 標頭 → 空行 → 內容」的格式拼裝。範例中還開啟了 chunked 串流模式,讓大檔案不必先全部載入記憶體。

public static String uploadFile(String uploadUrl, String filePath) {
    String nextLine = "\r\n";
    String dividerStart = "--";
    String boundary = "******";
    try {
        URL url = new URL(uploadUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setChunkedStreamingMode(1024 * 256);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Charset", "UTF-8");
        // 必須在 Content-Type 中指定分隔符
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
        dos.writeBytes(dividerStart + boundary + nextLine);
        dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
                + filePath.substring(filePath.lastIndexOf("/") + 1) + "\"" + nextLine);
        dos.writeBytes(nextLine);
        FileInputStream fis = new FileInputStream(filePath);
        byte[] buffer = new byte[1024 * 32];
        int count;
        while ((count = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, count);
        }
        fis.close();
        dos.writeBytes(nextLine);
        dos.writeBytes(dividerStart + boundary + dividerStart + nextLine);
        dos.flush();
        InputStream is = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String result = br.readLine();
        dos.close();
        is.close();
        connection.disconnect();
        return result;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

伺服器端:Golang 收檔

Golang 的 net/http 已經內建 multipart 解析能力,r.FormFile() 一行就能取得檔案本體與檔案標頭,剩下的就是讀成位元組再寫檔。

package webserver

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
)

func UpLoadBase() {
    fmt.Println("This is uploadbase")
    http.HandleFunc("/httpUploadFile", handleUploadFile)
    err := http.ListenAndServe(":8086", nil)
    if err != nil {
        fmt.Println("ListenAndServe error: ", err.Error())
    }
}

func handleUploadFile(w http.ResponseWriter, r *http.Request) {
    fmt.Println("client:", r.RemoteAddr)
    file, fileHeader, err := r.FormFile("file")
    if err != nil {
        log.Fatal("FormFile:", err.Error())
        return
    }
    defer func() {
        if err := file.Close(); err != nil {
            log.Fatal("Close:", err.Error())
        }
    }()
    fileName := fileHeader.Filename
    if fileName == "" {
        log.Fatal("Param filename cannot be null.")
        return
    }
    bytes, err := ioutil.ReadAll(file)
    outputFilePath := "/home/admin/桌面/" + fileName
    err = ioutil.WriteFile(outputFilePath, bytes, os.ModePerm)
    if err != nil {
        log.Fatal("WriteFileError:", err.Error())
        return
    }
    w.Write([]byte("上傳檔案成功!"))
}

實作時容易踩到的坑

第一,Android 4.4 以後預設禁止在主執行緒進行網路連線,記得把上傳邏輯放進背景執行緒或 AsyncTask。

第二,需要網路權限,AndroidManifest.xml 中別忘了加入 android.permission.INTERNET。

第三,伺服器端的 filename 直接來自用戶端,若無條件寫入磁碟會形成 Path Traversal 風險。正式環境請先做一次檔名清洗,只保留 basename。

第四,範例中的 log.Fatal 會直接結束整個行程,在實際服務中應該改成回傳錯誤訊息並 return。

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