转发文件上传

时间:2016-09-26 22:35:07

标签: http file-upload go multipartform-data

我正在处理一个接受上传的api端点,然后立即转发到另一个API。我不想在任何地方将文件写入磁盘,但我不确定将文件临时存储在内存中的方式也是正确的。我能找到的所有示例都将文件保存到磁盘。我已经发布了我在下面做的事情。我从第二个API返回的响应是我没有发布文件,但我可以看到它正在接收" userID"领域。有人可以指出我做错了什么,并可能建议这是否是最好的解决方法?

路线处理程序

func (r *Routes) forwardFile(w http.ResponseWriter, req *http.Request){ 
    parameters := mux.Vars(req)
    userID := parameters["userID"]

    const maxFileSize = 1 * 1024 * 1024 // 1MB

    // pull in the uploaded file into memory
    req.ParseMultipartForm(maxFileSize)


    file, fileHeader, err := req.FormFile("fileUpload")
    if err != nil {
        encodeResponse(w, req, response{obj: nil, err: err})
        return
    }
    defer file.Close()

    success, err := service.DoForwardFile(userID, file, fileHeader)
    encodeResponse(w, req, response{obj: success, err: err})
}

服务处理程序

func (b *base) DoForwardFile(userID int, file multipart.File, fileHeader *multipart.FileHeader) (FileForwardedResponse, error) {
    // start building our request to forward the file
    var resp *http.Response
    defer func() {
        if resp != nil {
            resp.Body.Close()
        }
        reportStat.Complete(0)
    }()

    // build a form body
    body := &bytes.Buffer{}
    bodyWriter := multipart.NewWriter(body)

    // add form fields
    bodyWriter.WriteField("userID", userID)

    // add a form file to the body
    fileWriter, err := bodyWriter.CreateFormFile("fileUpload", fileHeader.Filename)
    if err != nil {
        return FileForwardedResponse{}, err
    }
    // copy the file into the fileWriter
    _, err = io.Copy(fileWriter, file)
    if err != nil {
        return FileForwardedResponse{}, err
    }

    // Close the body writer
    bodyWriter.Close()

    // build request url
    apiURL := fmt.Sprintf("%s/v2/users/%d/files", config.APIURL, userID)

    // send request
    client := &http.Client{Timeout: time.Second * 10}
    req, err := http.NewRequest("POST", apiURL, body)
    resp, err = client.Do(req)

    ... 


  }

1 个答案:

答案 0 :(得分:0)

您未为请求设置Content-Type。即使标题自动设置为multipart/form-data,它也会丢失数据边界。

req, err := http.NewRequest("POST", uri, body)
if err != nil {
    return FileForwardedResponse{}, err
}
req.Header.Set("Content-Type", bodyWriter.FormDataContentType())
...