我编写了一个 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 关注
- 86 浏览
添加回答
举报
0/150
提交
取消