Search code examples
node.jsexpresshttpfile-uploadapi-design

What is the best way to send files through HTTP?


I am working on web api in node.js and express and I want to enable users to upload images. My api is using JSON requests and responses but when it comes to uploading images I don't know which option is a better one. I can think of two ideas:

  • encode images as a base64 strings and send them as a JSON (like {"image": "base64_encoded_image"})

  • use multipart/form request and handle the request with a help of packages like multer

I've been reading some articles and other questions related to my issue and I'm still struggling to choose one approach over the other. Encoding image and sending it with JSON increases the size of data by about 25% (that's what I've read) but using multipart seems weird to me as all other endpoints on my api use JSON.


Solution

  • The multipart/formdata approach has certain advantages over the Base64 encoding one.

    First and foremost disadvantage of using Base64 approach is the 30% increase in size of data, while this may not be significant for files of small size but it will definitely matter if you are sending large files and storing them on storage spaces (will increase your cost/data-consumption). Also packages like multer provide you with certain functionalities like - checking the type of file (jpg, png, etc) and set size limit on files etc. And they are quite easy to implement as well with a lot of tutorials and guides present online.

    Furthermore, converting image to Base64 string increases computation overhead on user's machine especially if the file is large.

    I would advise you to use multipart/form-data approach for your case.