編輯:關於 Android 程式設計
本文示範一組最經典的搭配:Android 端作為用戶端,用 HttpURLConnection 發送 multipart 請求;Golang 端作為伺服器,接收並落地存檔。整個流程不依賴任何第三方套件。
上傳檔案的關鍵在於三件事:請求方法必須是 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 的 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。
Android Universal Image Loader 使用完全指南
一、功能介紹 1.1 Android Universal Image Loader Android Universal Image Loader 是一個強大且可高度自訂的
Android 自定義 View 繪圖:用 Path 實作無縫拖影動畫
幾天前在「Android 繪圖之漸隱動畫」中,我用畫線的方式做出漸隱效果,但留了個問題:畫筆粗度大於 1 時,相鄰線段之間會出現裂隙。這次改用 Path 重寫,效果改善很
Mina SSLFilter 安全加密過濾器詳解
本文譯介自 Apache Mina 用戶指南第 11 章「SSL Filter」,系統梳理 SslFilter 的作用、工作原理與源碼要點。 SslFilter 負責通過
深入解析 Android 聯繫人提供者(Contacts Provider)架構與開發指南
聯繫人提供者(Contacts Provider)是 Android 平台上強大且靈活的元件,肩負著管理裝置聯繫人資料中央儲存庫的重任。它既是系統聯繫人應用背後的資料來源