我撰寫了一個 HTTP 請求來發送檔案內容:
// HTTP request.
req, err := UploadRequest("/slice", "file", pth)
通過這個功能:
// Creates a new file upload http request.
// https://gist.github.com/mattetti/5914158/f4d1393d83ebedc682a3c8e7bdc6b49670083b84
func UploadRequest(uri string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path) // handle err...
fileContents, err := ioutil.ReadAll(file) // handle err...
fi, err := file.Stat() // handle err...
file.Close()
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, fi.Name()) // handle err...
part.Write(fileContents)
err = writer.Close() // handle err...
request, err := http.NewRequest("POST", uri, body)
request.Header.Add("Content-Type", writer.FormDataContentType())
return request, err
}
問題
請求處理程式接收請求正文:
func Handler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
body, err := ioutil.ReadAll(r.Body) // I have request body :)
}
}
除錯器顯示請求body是:

我試圖在\r\n\r\n字符之后獲取正文資料。我怎樣才能做到這一點?
試過
這是試過的,但沒有奏效:
err = r.ParseForm() // Handle err...
stl := r.PostForm.Get("file") // "file" param name is hard-coded.
// `stl` is just an empty string.
uj5u.com熱心網友回復:
使用Request.FormFile決議多部分請求正文并回傳其中的檔案:
func Handler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
f, h, err := r.FormFile(paramName)
if err != nil {
// TODO: Handle error
}
data, err := ioutil.ReadAll(f)
if err != nil {
// TODO: Handle error
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/404487.html
標籤:
上一篇:如果值已設定且為假,則轉到模板
