處理檔案上傳
application/x-www-form-urlencoded 表示在傳送前編碼所有字元(預設)
multipart/form-data 不對字元編碼。在使用包含檔案上傳控制元件的表單時,必須使用該值。
text/plain 空格轉換為 "+" 加號,但不對特殊字元編碼。<html>
<head>
<title>上傳檔案</title>
</head>
<body>
<form enctype="multipart/form-data" action="/upload" method="post">
<input type="file" name="uploadfile" />
<input type="hidden" name="token" value="{{.}}"/>
<input type="submit" value="upload" />
</form>
</body>
</html>http.HandleFunc("/upload", upload)
// 處理/upload 邏輯
func upload(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) //取得請求的方法
if r.Method == "GET" {
crutime := time.Now().Unix()
h := md5.New()
io.WriteString(h, strconv.FormatInt(crutime, 10))
token := fmt.Sprintf("%x", h.Sum(nil))
t, _ := template.ParseFiles("upload.gtpl")
t.Execute(w, token)
} else {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
fmt.Fprintf(w, "%v", handler.Header)
f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666) // 此處假設當前目錄下已存在 test 目錄
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
}
}
客戶端上傳檔案
links
Last updated