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.
Therefore, we can use form-data for sending large binary or non-ASCII text to the server. The raw data type sends any plain text or JSON to the server, as the name suggests. It supports multiple content types, and Postman will send the raw data without any modifications compared to the other data types.
To pass the Json and Multipart in the POST method we need to mention our content type in the consume part. And we need to pass the given parameter as User and Multipart file. Here, make sure we can pass only String + file not POJO + file. Then convert the String to Json using ObjectMapper in Service layer.
Multipart/form-data should be used for submitting forms that contain large files, non-ASCII data, and large binary data. Moreover, multipart/form-data can be used for forms that are presented using representations like spreadsheets, Portable Document Format, etc. i.e other than HTML.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With