Hello Developers,
In this demonstration, I will show you how to use multipart/form-data in ExpressJs. First, you have to install NodeJs in your working environment. Follow the tutorial: (Tutorial Link)
First, create a folder and open the command prompt. Then run the below command:
Then create a file named index.js. Run the below command first.
npm init --y
After that, run the command to install express js.
npm install express --save
First, put the below code into the index.js file.
var express = require('express');
app = express();
After installing the node, we have to use a package called Multer. Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of the busboy for maximum efficiency.
NOTE: Multer will not process any form which is not multipart (multipart/form-data).
For installing Multer, run the below command:
npm install --save multer
After that write some code in the index.js file. In the first line call express and multer and then initialize.
/index.js
var express = require('express');
var multer = require('multer');
app = express();
var multer = multer();
Then we need to call multer.array().
Also, we need to call the express.static('public').
var express = require('express');
var multer = require('multer');
app = express();
var multer = multer();
var multer = require('multer');
var multer = multer();
app.use(multer.array());
app.use(express.static('public'));
Then call http://localhost:8000/multipartData.
var express = require('express');
var multer = require('multer');
app = express();
var multer = multer();
var multer = require('multer');
var multer = multer();
app.use(multer.array());
app.use(express.static('public'));
app.post("/multipartData", function name(request, response) {
let jsonData = request.body;
response.send(JSON.stringify(jsonData));
})
app.listen(8000, function () {
console.log('Server Run Success');
});
After all that, we call the listen()
method to set the port. After that run the below command in the command line.
node index.js
Run the below line in the PostMan software, the end-point represents the parameter created in the app.get("/multipartData")
method. Pass a value in a key like the below image.
http://localhost:8000/multipartData
Hope this might help in the development journey.
Read More: Learn some important functions in ExpressJs
The output is given below: