File upload in any web application is a crucial part of the development. Every beginner developer faces some issue while building an API for file upload. If you follow the right procedure then you can easily build an API to upload the single or multiple files to the server. In this article, I am going to explain to you how to build a RESTful API to upload file in Node.js using the express framework.

Before going further with this article, I am assuming that you know how to install node.js and how to use the express framework and know about the ES6+ features of the JavaScript.

To build RESTful API for file upload in the node.js, we are going to use the multer middleware.

What Is Multer

Multer is a node.js middleware for handling the multipart/form-data to upload the file in the server. It processes only those form which has only multipart/form-data.

How Multer Works

Multer adds a body and files or file object to the node.js request object. The body object of the multer contains the value of the text fields of the form and files or file object contains the file information of the uploaded file.

How To Install Multer

To install the multer in your node.js application you can simply use the below command in your terminal.

npm install multer --save

How To Use Multer For File Upload In Node.js

For this tutorial, I am not focusing on how to structure your node.js project. Here, I am using only a single file which is responsible for the all functionalities like starting the node.js app, routing in express, the configuration of multer.

First, go to the working directory of your project and create a file with name file_upload.js

touch file_upload.js

After creating the file, create a package.json file using the below command.

npm init

Above command will create a package.json file which is used as a manifest of your application.

Now run the below command to install the required npm modules and libraries.

npm install express body-parser multer --save

After installing the required modules, create a folder in the root public and inside this folder create another folder upload, where we upload all our files.

Starting Express Server

Now write the below code to set up the initial things for the file upload in node.js and start the express server.

// import the required modules const express = require('express'), bodyParser = require('body-parser'), multer = require('multer'); // define multer storage configuration const storage = multer.diskStorage({ destination : function(req,file,callback){ callback(null, './public/upload/'); }, filename: function(req,file,callback){ callback(null, file.fieldname + '-' + Date.now()); } }); const upload = multer({ storage : storage}); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.listen(5010,function(){ console.log("server is running on port 5010"); });

The Above code is pretty self-explanatory for the node.js developers. We are running our express app on port 5010.

Upload Single File In Node.js

Now let’s create an API for the single file upload in node.js. Below is the code for single file upload which is again self-explanatory.

//file upload api app.post('/api/upload/single', upload.single('singleFile'), (req,res) => { try{ const file = req.file; if (!file) { res.status(400).json({ "status": "failed", "code" : "400", "message" : "Please upload file" }); } res.status(200).json({ "status": "success", "code" : "200", "message" : "file uploaded successfully" }); }catch(err){ console.log(error.message); res.status(200).json({ "status": "failed", "code" : "500", "message" : error.message }); } });

In the above code, we are adding the multer.single(‘singleFile’) middleware in our routes which handle all the file upload things and save the file to its given location.

After adding the above code now, our final code will look like below

// import the require modules const express = require('express'), bodyParser = require('body-parser'), multer = require('multer'); // define multer storage configuration const storage = multer.diskStorage({ destination : function(req,file,callback){ callback(null, './public/upload/'); }, filename: function(req,file,callback){ callback(null, file.fieldname + '-' + Date.now()); } }); const upload = multer({ storage : storage}); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); //single file upload api app.post('/api/upload/single', upload.single('singleFile'), (req,res,next) => { try{ const file = req.file; if (!file) { res.status(400).json({ "status": "failed", "code" : "400", "message" : "Please upload file" }); } res.status(200).json({ "status": "success", "code" : "200", "message" : "file uploaded successfully" }); }catch(err){ console.log(error.message); res.status(200).json({ "status": "failed", "code" : "500", "message" : error.message }); } }); app.listen(5010,function(){ console.log("server is running on port 5010"); });

Test the API

For testing the API, I am using the postman app. If you don’t know what is postman then you should know about this and learn how to use Postman to test your API.

API URL For Single File Upload

localhost:5010/api/upload/single

If everything goes well then, in the Postman, you will see the below response which means your file uploaded successfully in the server destinated path(public/upload).

Upload Multiple File In Node.js

To upload the multiple files to the server, we just need to add multer.array() middleware instead of the multer.single() middleware in the express app routes.

//multiple file upload api app.post('/api/upload/multiple', upload.array('multipleFile',4), (req,res,next) => { try{ const files = req.files; if (!files) { res.status(400).json({ "status": "failed", "code" : "400", "message" : "Please upload file" }); } res.status(200).json({ "status": "success", "code" : "200", "message" : "file uploaded successfully", "data" : files }); }catch(error){ res.status(200).json({ "status": "failed", "code" : "500", "message" : error.message }); } });

API URL For Multiple File Upload

localhost:5010/api/upload/multiple

Test Multiple File Upload

How To Filter File In Multer File Upload

Till now, we created the APIs for single and multiple file upload successfully. But these are the simple APIs without any validation on the files object like file type validation, file size validation and another type of validation.

To add these validations, multer has a property called fileFilter. It controls which files should be uploaded and which files should be skipped.

const fileFilter = function (req, file, cb) { // accept image only if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) { return cb(new Error('Only image files are allowed!'), false); } cb(null, true); };

Above is the simple code which allows only the image files and skips the rest files.

Now after adding the fileFilter function our new code will look like below

// import the require modules const express = require('express'), bodyParser = require('body-parser'), multer = require('multer'); // define multer storage configuration const storage = multer.diskStorage({ destination : function(req,file,callback){ callback(null, './public/upload/'); }, filename: function(req,file,callback){ callback(null, file.fieldname + '-' + Date.now()); } }); const fileFilter = function (req, file, callback) { // accept image only if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) { return callback(new Error('Only image files are allowed!'), false); } callback(null, true); }; const upload = multer({ storage : storage, fileFilter: fileFilter}); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); //single file upload api app.post('/api/upload/single', upload.single('singleFile'), (req,res,next) => { try{ const file = req.file; if (!file) { res.status(400).json({ "status": "failed", "code" : "400", "message" : "Please upload file" }); } res.status(200).json({ "status": "success", "code" : "200", "message" : "file uploaded successfully", "data" : file }); }catch(err){ console.log(error.message); res.status(200).json({ "status": "failed", "code" : "500", "message" : error.message }); } }); //multiple file upload api app.post('/api/upload/multiple', upload.array('multipleFile'), (req,res,next) => { try{ const files = req.files; if (!files) { res.status(400).json({ "status": "failed", "code" : "400", "message" : "Please upload file" }); } res.status(200).json({ "status": "success", "code" : "200", "message" : "file uploaded successfully", "data" : files }); }catch(error){ console.log(error.message); res.status(200).json({ "status": "failed", "code" : "500", "message" : error.message }); } }); app.listen(5010,function(){ console.log("server is running on port 5010"); });

Conclusion

So we finally learned how file upload in Node.js works and how to filter the upload file type and limit the files for the multiple files.

No doubt multer makes the file upload handling in node.js so much simpler. Multer is very easy to understand, flexible and easy to configure for different use cases.

This is the very basic tutorial on the file upload, in the real-world application, you will face other issues like how to handle the large file easily, how to do the upload large file and read them effectively but the basic concept is same in all the situations which you already learned in this tutorial.

If you are facing any issue or have any doubts/suggestions then let me know in the comment section below or can join our Facebook group where like-minded people will try to solve your queries. 🙂

Happy Coding, Happy Learning 🙂