File Upload in Node.js
This is the article all about the file upload in Node.js. A large number of applications allow users to upload profile pictures and other files. Therefore, files upload is a common requirement while building a REST API with Node.js & Express.
file upload in node js, Upload Files or Images to Server Using Node.js, NodeJS File Upload Using Multer, File Upload With Multer in Node.js and Express, node js rest api file upload, express file upload stream, node.js express upload image example.
Checkout more articles on React JS:
Today we will show you how to upload file using REST API in Node.js. To manage the file upload on server, we are going to use express framework and middleware called multer. This middleware is designed for handling the multipart/form-data only.
Way to implement file upload in Node.js
- Setup REST API in Node.js using Express
- Install a dependency
- Handle multer storage
- Handle single file upload
- Handle multiple file upload
- Output
1. Setup REST API in Node.js using Express
We will be using the Node.js using Express framework to upload file. So We’ll need to have REST API in Node.js. Kindly follow the link below if you don’t know how to create REST API in Node.js using Express framework.
2. Install a dependency
We have to install the following packages to create API for file upload.
- body-parser – Node.js request body parsing middleware which parses the incoming request body before your handlers, and make it available under req.body property. In other words, it simplifies the incoming request.
- cors – It’s an Express middleware for enabling Cross-Origin Resource Sharing requests. Just because of it, We can access the API in different applications.
- 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 busboy for maximum efficiency.
Run the following command to install the required dependencies.
1 | npm install body-parser cors multer --save |
On successful installation, You have to use it in server file to enable the middleware and handle the request. Checkout the below code of “server.js” where we use it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | var express = require('express'); const cors = require('cors'); const bodyParser = require('body-parser'); var app = express(); var port = process.env.PORT || 4000; // enable CORS app.use(cors()); // parse application/json app.use(bodyParser.json()); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({extended: true})); // request handlers app.get('/', (req, res) => { res.send('Welcome to the first Node.js Tutorial! - Clue Mediator'); }); app.listen(port, () => { console.log('Server started on: ' + port); }); |
3. Handle multer storage
As you know, we will be using the multer package to manage the uploads and already installed it in project, So the next step should be the create folder as “uploads” in the root directory where all our files will be saved.
Multer gives the option of storing files to server and also set the new identifier to the file, as shown below.
1 2 3 4 5 6 7 8 9 10 | // handle storage using multer var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads'); }, filename: function (req, file, cb) { cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`); } }); var upload = multer({ storage: storage }); |
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static
function, specify a mount path for the static directory, as shown below:
1 2 | // serving static files app.use('/uploads', express.static('uploads')); |
4. Handle single file upload
Now we need to create a POST request in “server.js” file to handle the single uploaded file request. Following code will be used to manage it.
1 2 3 4 5 6 7 8 | // handle single file upload app.post('/uploadfile', upload.single('dataFile'), (req, res, next) => { const file = req.file; if (!file) { return res.status(400).send({ message: 'Please upload a file.' }); } return res.send({ message: 'File uploaded successfully.', file }); }); |
5. Handle multiple file upload
In order to handle multiple files with Multer is similar to a single file upload, but rather than .single()
we are using .array(selector,fileLimit)
of Multer.
In below code we mentioned upload.array('dataFiles', 10)
that means multer will accept array of files limiting to max 10 file at each time. You can increase/decrease the number as you may need. Rest of the code is the same as single file upload.
1 2 3 4 5 6 7 8 | // handle multiple file upload app.post('/uploadmultifile', upload.array('dataFiles', 10), (req, res, next) => { const files = req.files; if (!files || (files && files.length === 0)) { return res.status(400).send({ message: 'Please upload a file.' }); } return res.send({ message: 'File uploaded successfully.', files }); }); |
6. Output
Finally, at last your “server.js” should look like below. You can have a test it with postman or any other tools.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | var express = require('express'); const path = require('path'); const cors = require('cors'); const bodyParser = require('body-parser'); const multer = require('multer'); var app = express(); var port = process.env.PORT || 4000; // enable CORS app.use(cors()); // parse application/json app.use(bodyParser.json()); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); // serving static files app.use('/uploads', express.static('uploads')); // handle storage using multer var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads'); }, filename: function (req, file, cb) { cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`); } }); var upload = multer({ storage: storage }); // handle single file upload app.post('/uploadfile', upload.single('dataFile'), (req, res, next) => { const file = req.file; if (!file) { return res.status(400).send({ message: 'Please upload a file.' }); } return res.send({ message: 'File uploaded successfully.', file }); }); // handle multiple file upload app.post('/uploadmultifile', upload.array('dataFiles', 10), (req, res, next) => { const files = req.files; if (!files || (files && files.length === 0)) { return res.status(400).send({ message: 'Please upload a file.' }); } return res.send({ message: 'File uploaded successfully.', files }); }); // request handlers app.get('/', (req, res) => { res.send('Welcome to the Node.js Tutorial! - Clue Mediator'); }); app.listen(port, () => { console.log('Server started on: ' + port); }); |