有很多关于在go中使用http.Request
发布文件的教程,但几乎总是这样开始:
file, err := os.Open(path)
if err != nil {
return nil, err
}
fileContents, err := ioutil.ReadAll(file)
也就是说,您将整个文件读入内存,然后将其转换为Buffer
并将其传递给请求,如下所示:
func send(client *http.Client, file *os.File, endpoint string) {
body := &bytes.Buffer{}
io.Copy(body, file)
req, _ := http.NewRequest("POST", endpoint, body)
resp, _ := client.Do(req)
}
如果您想发布一个大文件并避免将其读入内存,而是将文件以块的形式传输出来......你会怎么做?
答案 0 :(得分:7)
如果您需要设置Content-Length
,可以手动完成。以下代码段是将文件和额外参数作为流上传的示例(基于Buffer-less Multipart POST in Golang的代码)
//NOTE: for simplicity, error check is omitted
func uploadLargeFile(uri, filePath string, chunkSize int, params map[string]string) {
//open file and retrieve info
file, _ := os.Open(filePath)
fi, _ := file.Stat()
defer file.Close()
//buffer for storing multipart data
byteBuf := &bytes.Buffer{}
//part: parameters
mpWriter := multipart.NewWriter(byteBuf)
for key, value := range params {
_ = mpWriter.WriteField(key, value)
}
//part: file
mpWriter.CreateFormFile("file", fi.Name())
contentType := mpWriter.FormDataContentType()
nmulti := byteBuf.Len()
multi := make([]byte, nmulti)
_, _ = byteBuf.Read(multi)
//part: latest boundary
//when multipart closed, latest boundary is added
mpWriter.Close()
nboundary := byteBuf.Len()
lastBoundary := make([]byte, nboundary)
_, _ = byteBuf.Read(lastBoundary)
//calculate content length
totalSize := int64(nmulti) + fi.Size() + int64(nboundary)
log.Printf("Content length = %v byte(s)\n", totalSize)
//use pipe to pass request
rd, wr := io.Pipe()
defer rd.Close()
go func() {
defer wr.Close()
//write multipart
_, _ = wr.Write(multi)
//write file
buf := make([]byte, chunkSize)
for {
n, err := file.Read(buf)
if err != nil {
break
}
_, _ = wr.Write(buf[:n])
}
//write boundary
_, _ = wr.Write(lastBoundary)
}()
//construct request with rd
req, _ := http.NewRequest("POST", uri, rd)
req.Header.Set("Content-Type", contentType)
req.ContentLength = totalSize
//process request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
} else {
log.Println(resp.StatusCode)
log.Println(resp.Header)
body := &bytes.Buffer{}
_, _ = body.ReadFrom(resp.Body)
resp.Body.Close()
log.Println(body)
}
}
答案 1 :(得分:1)
事实证明,您实际上可以将*File
(或任何类似于流)的对象直接传递到NewRequest
。
请注意,请注意,NewRequest(如此处所示:https://golang.org/src/net/http/request.go?s=21674:21746#L695)实际上不会设置ContentLength
,除非流明确之一:
由于*File
不是其中之一,因此请求将在没有内容长度的情况下发送,除非您手动设置它,这可能会导致某些服务器丢弃传入请求的正文,从而导致在服务器上,当它似乎已从正确的方向发送时。