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
};
|
method: "post", url: `${SERVER_URL}route`, data: bodyFormData, headers: bodyFormData.getHeaders() }) .then(response => { // log response or save it }) .catch(e => { // handle errors }) |
Comments
Post a Comment