duangutang3940 2014-09-10 06:09
浏览 223
已采纳

Golang将多个文件添加到HTTP多部分请求

Currently i am streaming 2 multipart requests separately.

  1. Contains the file as a blob
  2. contains a json file as a description of the blob

How can i upload them at the same time with multipart?

this is the request that runs 2 times. I want to add the 2 files in this 1 request

 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
}
  • 写回答

1条回答 默认 最新

  • duanreng3439 2014-09-10 11:34
    关注

    You simply call CreateFormFile again (or CreateFormField) and write your json to the writer returned.

    j, err := writer.CreateFormFile("meta", h.DropRef + ".json")
    enc := json.NewEncoder(j)
    enc.Encode(some-struct-you-want-to-write-as-json)
    

    Just make sure you finish writing your first file before creating a new one, because according to the docs:

    After calling CreatePart, any previous part may no longer be written to.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?