File Upload in Node js using Multer is an important feature for any web application. Multer is a Node.js or express middleware, that makes it easy to handle multipart/form-data when your users upload files. When a website user uploads a file to a server, it is usually submitted via a form and encoded as multipart/form-data.
As I already said, Multer is Middleware for Express. Middleware is a piece of software which connects various applications or components of the software. Middleware runs in Express and sends incoming requests to the server. In our case, when uploading files Multer works as a helper.
In this tutorial, I’ll show you the basic procedure of File Upload in Node js using Multer.
Also Read: Drag and Drop File Upload using Dropzone JS, PHP & MySQL
File Upload in Node js using Multer
REQUIREMENTS
Project Setup
For this project we’ll be using the Node Express framework. You will, of course, need to have Node installed.
Create a directory for our project
2 3 4 |
mkdir file-upload-nodejs |
Move into the directory
2 3 4 |
cd file-upload-nodejs |
create a .json file that manages all the dependencies for our application
2 3 4 |
npm init |
Now, install Multer, Express, and the other necessary dependencies
2 3 4 |
npm install express multer body-parser nodemon |
Now create an app.js file
in app.js, we will initialize module, create an Express app, and create a server for connecting to browsers.
2 3 4 5 6 7 8 9 10 |
const express = require('express') const bodyParser= require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({extended: true})) //ROUTES WILL GO HERE app.listen(3000, () => console.log('Server started on port 3000')); |
Create your project routing file routes/upload.js
Multer Configuration
Add the multer object to your routing file
2 3 4 |
var multer = require('multer'); |
We will upload the file in public/uploads directory. So our multer will contain the following configuration:
Multer Storage, File size Limits and file Filter configuration
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 |
var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './public/uploads/') }, filename: function (req, file, cb) { cb(null, Date.now()+file.originalname) } }); // this code will handle file types like jpeg, jpg, and png const fileFilter=(req, file, cb)=>{ if(file.mimetype ==='image/jpeg' || file.mimetype ==='image/jpg' || file.mimetype ==='image/png'){ cb(null,true); }else{ cb(null, false); } } var upload = multer({ storage:storage, limits:{ fileSize: 1024 * 1024 * 5 // define limit 5mb max file upload size }, fileFilter:fileFilter }); |
Now the multer is ready to upload the file in public/uploads folder.
Create a routes/index.html file
Write all the code that will be served to the client to upload file.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My First App</title> </head> <body> <!-- SINGLE FILE --> <form action="/fileupload" enctype="multipart/form-data" method="POST"> <input type="file" name="image" /> <input type="submit" value="Upload"/> </form> </body> </html> |
App Routing
Now we will add the multer configuration in the routing file and add a post routing.
Copy and paste below code in routing file routes/upload.js
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 |
var express = require('express'); var router = express.Router(); var multer = require('multer'); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './public/uploads/') }, filename: function (req, file, cb) { cb(null, Date.now()+file.originalname) } }) const fileFilter=(req, file, cb)=>{ if(file.mimetype ==='image/jpeg' || file.mimetype ==='image/jpg' || file.mimetype ==='image/png'){ cb(null,true); }else{ cb(null, false); } } var upload = multer({ storage:storage, limits:{ fileSize: 1024 * 1024 * 5 }, fileFilter:fileFilter }); router.get('/',function(req,res){ res.sendFile(__dirname + '/index.html'); }); router.post("/fileupload",upload.single('image'),function(req,res,next){ const filename=req.file.filename; res.json({ message:"Image Uploaded Successfully", filename:filename }); }); module.exports=router; |
Now open your app.js file and search var app = express();
copy and paste below code after var app = express(); to set route
2 3 4 5 |
var uploadRouter = require('./routes/upload'); app.use('/', uploadRouter); |
So now preview complete code of file:
app.js
2 3 4 5 6 7 8 9 10 11 12 |
const express = require('express') const bodyParser= require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({extended: true})) //ROUTES WILL GO HERE var uploadRouter = require('./routes/upload'); app.use('/', uploadRouter); app.listen(3000, () => console.log('Server started on port 3000')); |
routes/upload.js
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 |
var express = require('express'); var router = express.Router(); var multer = require('multer'); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './public/uploads/') }, filename: function (req, file, cb) { cb(null, Date.now()+file.originalname) } }) const fileFilter=(req, file, cb)=>{ if(file.mimetype ==='image/jpeg' || file.mimetype ==='image/jpg' || file.mimetype ==='image/png'){ cb(null,true); }else{ cb(null, false); } } var upload = multer({ storage:storage, limits:{ fileSize: 1024 * 1024 * 5 }, fileFilter:fileFilter }); router.get('/',function(req,res){ res.sendFile(__dirname + '/index.html'); }); router.post("/fileupload",upload.single('image'),function(req,res,next){ const filename=req.file.filename; res.json({ message:"Image Uploaded Successfully", filename:filename }); }); module.exports=router; |
Now our code is ready for test.
Now open your terminal and run below command
2 3 4 5 6 |
node app.js or nodemon |
After running node app.js. You will get message:
node app.js
Server started on port 3000
Now open http://localhost:3000/ in your browser
Now select your image file and click on upload button. After successfully upload you will get following response on browser.
Conclusion:
I hope you found this tutorial helpful for your project. File Upload in Node js using Multer is an important feature for any web application. So Here we are, completed the basic file uploading using multer in node.js and express.js
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co