目前我正在分别发送2个多部分请求。
我如何使用multipart同时上传它们?
这是运行2次的请求。我想在这个1请求中添加2个文件
func(c *Client) Upload(h *UploadHandle) (*PutResult, error) {
bodyReader, bodySize, err := h.Read()
if err != nil {
return nil, fmt.Errorf("Failed to peek the body size %v", err)
}
if bodySize > constants.MaxDropSize {
return nil, errors.New("The size of the body is to big")
}
pipeReader, pipeWriter := io.Pipe()
writer := multipart.NewWriter(pipeWriter)
errChan := make(chan error, 1)
go func() {
defer pipeWriter.Close()
part, err := writer.CreateFormFile(h.DropRef, h.DropRef)
if err != nil {
errChan <- err
return
}
_, err = io.Copy(part, bodyReader)
if err == nil {
err = writer.Close()
}
errChan <- err
}()
uploadUrl := fmt.Sprintf("%s/drops/upload", c.Server)
req, err := http.NewRequest("POST", uploadUrl, pipeReader)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", writer.FormDataContentType())
req.Body = ioutil.NopCloser(pipeReader)
resp, err := c.Do(req)
if err != nil {
return nil, fmt.Errorf("Failed doing request: %v", err)
}
defer resp.Body.Close()
// Handling the error the routine may caused
if err := <-errChan; err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("The server responded with a status %d", resp.StatusCode)
}
return &PutResult{h.DropRef, bodySize}, nil
}
答案 0 :(得分:2)
您只需再次调用CreateFormFile
(或CreateFormField
)并将您的json写入返回的作者。
j, err := writer.CreateFormFile("meta", h.DropRef + ".json")
enc := json.NewEncoder(j)
enc.Encode(some-struct-you-want-to-write-as-json)
请确保在创建新文件之前完成第一个文件的编写,因为根据docs:
调用CreatePart后,任何以前的部分都可能不再写入。