Home > Software engineering >  Include client multi part form file in new POST request
Include client multi part form file in new POST request

Time:09-27

Think I might be missing something obvious here. I'm attempting to grab the file from a client request hitting my server and forwarding that to an external API for processing by creating a new multipart request and copying the file over. In this case, the API is looking for a FormFile under the "files" key. The receiving API keeps telling me the file has invalid mime type application/octet-stream

API Call Documentation

func forwardFile(r *http.Request) (string, error) {
    file, fileHandler, err := r.FormFile("image")
    if err != nil {
        return "", err
    }
    defer file.Close()

    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)

    part, err := writer.CreateFormFile("files", fileHandler.Filename)
    if err != nil {
        return "", err
    }

    if _, err := io.Copy(part, file); err != nil {
        return "", err
    }

    writer.Close()

    req, _ := http.NewRequest("POST", newUploadUrl, body)
    req.Header.Add("Content-Type", writer.FormDataContentType())
    client := &http.Client{}
    response, err := client.Do(req)
}

Thank you for your time.

CodePudding user response:

I guess you need to change your content type to multipart/form-data

CodePudding user response:

Solved it by creating a MIMEHeader and populating the disposition and content type myself, see below:

partHeader := textproto.MIMEHeader{}
disposition := fmt.Sprintf("form-data; name=\"files\"; filename=\"%s\"", fileHandler.Filename)
partHeader.Add("Content-Disposition", disposition)
partHeader.Add("Content-Type", "image/png")
part, err := writer.CreatePart(partHeader)

if _, err := io.Copy(part, file); err != nil {
  log.Print("Error copying")
  return "", err
}
  • Related