Node.js Sending Multipart/form-data from server side(backend)
A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.
In terms of backend or server side perspective, uploading a multipart/form-data can be challenging. Developers who are new, may struggle to understand how to call an api endpoint which consist of Content-Type: multipart/form-data.
But, don’t worry it is same as calling the api end point with Content-Type: application/json. But the difference is that we have to append all the file into the form using package called form-data.
What we will be using:
1. form-data:
Form data is a library to create readable "multipart/form-data"
streams. Can be used to submit forms and file uploads to other web applications.
2. node-fetch:
node-fetch is a npm package to make Http request.
const FormData = require('form-data');
const http = require('http');
const form = new FormData();
const fs = require('fs');form.append('file1', 'fileData');
form.append('my_buffer', new Buffer(10)); //appending buffer in key my_buffer
form.append('my_logo', fs.createReadStream('your_image_location')); //appending image in key 'my logo'const uploadResponse = await fetch(url_to_send_request, {method: 'POST', body: form });
Here the form-data will convert our request into something like this and we can receive the response.
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
Thank you!!
REFERENCES: