我編寫了一個 HTTP 請求來發送文件內容:// HTTP request.req, err := UploadRequest("/slice", "file", pth)通過這個函數:// Creates a new file upload http request.// https://gist.github.com/mattetti/5914158/f4d1393d83ebedc682a3c8e7bdc6b49670083b84func 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.http去郵政
1 回答

慕容森
TA貢獻1853條經驗 獲得超18個贊
使用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
}
}
}
- 1 回答
- 0 關注
- 104 瀏覽
添加回答
舉報
0/150
提交
取消