15

I noticed there are (at least) two ways of uploading a file to a HTTP server via an API.

You can use multipart/form-data (which is what browsers do natively for file upload HTML inputs), but you can also POST the file content inside the request body (perhaps with the correct Content-Type request header).

What are the pros and cons of each method (in all generality, not from a browser)?

Multipart requests for instance – depending on which http or networking library you use in your programming environment (I use Node.js on the server side and Swift on the client side) – seem to be a bit more complex to create and then parse.

julien_c
  • 4,942
  • 5
  • 39
  • 54
  • Check http://stackoverflow.com/questions/29659154/what-is-the-best-way-to-upload-files-in-a-modern-browser/ – vtortola Sep 01 '15 at 16:40
  • @vtortola not really an answer to this question. I'm not asking about any client-side networking implementations, just about the http methods. – julien_c Sep 02 '15 at 09:17

1 Answers1

24

The only difference on the protocol level is that multipart/form-data requests must adhere to RFC 2388 while a custom typed request body can be arbitrary.

The practical implication from this is that a multipart/form-data request is typically larger: While clients are technically allowed to use a non-7bit content-transfer-encoding, base64 is used by most. The MIME headers generate additional overhead that can become a bottleneck if many small files are uploaded. Note that support for multipart/form-data file uploads in existing clients/libraries is far more widespread. You should always provide it as a fallback if you are not sufficiently certain about the featureset of your clients and intermediate hosts (proxy servers). Especially keep in mind that if you are designing an API for third parties that other developers will already be familiar with multipart/form-data and have libraries at hand to work with that.

Phillip
  • 13,448
  • 29
  • 41
  • 1
    Need an opinionated answer though, rather than "you decide based on this stuff" – Jus12 Jan 02 '20 at 07:50
  • If in doubt, go with `multipart/form-data`. – Phillip Jan 02 '20 at 13:31
  • I'm very likely not understanding this answer. From what you said it looks like the when using multipart form data while uploading a file, browsers generally encode with base64 which isn't right AFAIK and it should be raw binary instead. The RFC link you posted says that: "the default for mail transport is the 7BIT encoding", but doesn't say anything for files – Giacomo Cerquone Aug 11 '22 at 20:06
  • Notable that it depends where the file is coming from. If the file is always coming from a frontend UI, multipart form-data makes sense. If the file is coming from a backend server, it is unlikely to be packaged as multi-part form data. – Llama D'Attore May 24 '23 at 15:37