Can I have a body and a file in the Form-Data of a http request

Viewed 1036

I'm working in a Go Lang REST API repo.

I'm wanting to build an endpoint that will take in a file (as part of the form-data, so I suppose I'll use request.FormFile('my-file-key')). This endpoint should also take in a body of a JSON model (which i suppose would be decoded with something like this:

var myData model.MyModel
json.NewDecoder(request.Body).Decode(&myData)

But I'm running into a lot of issues. Is it even possible to send both a body and a file in the form-data with a http request?

If I try to send both I get errors from FormFile saying that it can't find the file of the key name (but if I send the exact same request without a body, this error doesn't happen). I guessing it's having trouble decoding the request.

1 Answers

What you need is a multipart request. One part can be JSON data, and the other part the file data.

If you're using a Go client to prepare the request, you need to use the mime/multipart package to create a Writer, then use CreatePart to create the JSON part, then the file part, and submit the request to the server.

On the decoding side: since the body is JSON you cannot parse it as a form. You have to use a multipart.Reader to read from the body after you parse the headers. Again, from that reader you get a Part, and read the data from that part. You'll get two parts, one for the JSON data and one for the file data.

Related