Multipart HTTP requests using the FormData and Fetch APIs

I was recently trying to implement something that had to upload a file along with a JSON object. My initial thought was to just include the file inside the object as a base 64 string. This worked fine for smaller files but broke down with larger ones. Large strings are handled poorly in some browsers which caused the UI to lag. Files had to converted to base 64 in browser which created additional overhead.

I knew the best way to transfer binary data on the browser was using input forms with the file type. It would solve these issues and the browser perform much of the heavy lifting when it came to the lower level. However, the hacks required in order to integrate it seemed intolerable. The last time I had done something similar, I remember having to create invisible forms and do all sorts of DOM manipulation to get something working.

Luckily, newer browsers have address this problem by providing the FormData API. It gets you out of the nitty gritty of having to always use HTML when creating these sorts of requests. It's easy to convert JavaScript objects to this and Fetch serializes it natively.

Sometimes, It's the little things like this that make developing in JavaScript in the current year nice.

Bret Lowrey

Code is like a war - the best code is one never written.

Florida, USA