2

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 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.