正在解析包含文件内容的 POST 请求正文
Parsing POST request body containing file content
我编写一个 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.
使用 Request.FormFile 解析多部分请求正文和 return 中的文件:
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
}
}
}
我编写一个 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.
使用 Request.FormFile 解析多部分请求正文和 return 中的文件:
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
}
}
}