How to send a file from a Node.js server with axios using FormData

Sending a file from a server as a request to another server. 

Seems like a pretty common scenario. If the file is large, I consider it an anti-pattern most of the time, but there are cases when there is no better choice.

Especially if the top management in your 'agile' team are just concerned about delivering a product to the client asap without considering the possible issues that would arise from not compressing such huge payloads, let alone allotting developers in the team the time to solve such problems.

But this post isn't a rant about how several 'certified' practitioners of agile methods apply the opposite of the patterns they were supposed to have learnt.

Without further ado, let's begin.


Axios is a popular promise based HTTP client. When sending a file like a pdf as a request to another server which might expect the file in the files array of the request, you will also have to use FormData, which does not have native support in Node.js.

Here's a snippet of how the form data object should be built -

const bodyFormData = new FormData(); bodyFormData.append("simpleBodyParam", simpleValue); bodyFormData.append("anotherBodyParam", anotherValue); bodyFormData.append("file", pdfAsBufferOrBase64, fileAttributes);

The first two values are basically a key-value pair like what you'd send in a raw body request. The fileAttributes object should be specified as follows -

const fileAttributes = {     filename: `${cuteFileName}`,     contentType: "application/pdf" ----> This here is très important };
If you don't specify the contentType, the file will not be received in the file array buffer.
The contentType could be a function that returns the correct mimetype for the file you're handling.

Now that the form data is built, let's send the request with axios!
    axios({
    method: "post",     url: `${SERVER_URL}route`,     data: bodyFormData,     headers: bodyFormData.getHeaders()     })     .then(response => {     // log response or save it     })     .catch(e => {     // handle errors     })

And that's it. You just built a solution to send a file to a server from Node.js using some neat open-source libraries. Pat yourself on the back and try to make libraries of your own to make others' lives easier. Or let GPT-3 (GPT-n?) figure it out.

Comments

Popular posts from this blog

How I got a 21% return on investment by investing in the NSE equity market without any experience

Goodbye Tofu(⏔)? - Google's Noto Project

Password authentication through contact!