Node.js File Upload: This tutorial is based on uploading files to the server in Node.js. You will learn to upload a single file at a time through this tutorial. Even you can validate the uploading file type. Every step is explained with the MVC Pattern. So, It is very easy to understand & use for your project.
There are lots of modules in npm to upload files to the server. But you should use the Multer module for uploading the file. Because It is the most popular & easy to implement in Node.js Express. So, Before using the Multer module, you have to know about the Multer Module with the following points.
- Multer can handle multipart/form-data for uploading files.
- Multer will not work without declaring enctype=”multipart/form-data” within the form tag.
How to Upload File Using Node.js & Express
You can easily upload the file through the following steps that are very simple to understand.
Learn also –
How to store Image in MySQL Database using Node.js
How to display Image from MySQL Database in Node.js
1. Install Express Application
First of all, Install Basic Express Application and create more required folders & file
nodeapp/ |__controllers/ | |__upload-controller.js |__public/ | |__files/ |__middlewares/ | |__upload-middleware.js |__routes/ | |__upload-route.js |__views/ | |__upload-form.ejs
2. Install Express Multer
First of all, Install multer module using the following command with npm
npm install --save multer
3. Create File Upload Form
File Upload form must have the following attribute
- method=”POST” – To upload the file through the post method
- enctype=”multipart/form-data” – to handle file uploading
- name=”file – It is the name of the file input Field
File Name – upload-form.ejs
<!DOCTYPE html> <html> <body> <form action="/upload" method="POST" enctype="multipart/form-data"> <label>Avatar</label> <input type="file" name="file"> <button type="submit">Upload</button> </form> </body> </html>
4. Upload File to the Folder
You should create a middleware to upload file to the folder using the following points –
- Create a folder
middlewares
- Also, create a file
upload-middleware.js
in themiddlewares
- Declare image folder path in the code
cb(null, 'image_folder_path')
. Herepublic/files/
is the path where the file will be uploaded.
File Name – upload-middleware.js
var multer = require('multer'); module.exports.files={ storage:function(){ var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'public/files/') }, filename: function (req, file, cb) { cb(null, file.originalname) } }) return storage; }, allowedFile:function(req, file, cb) { if (!file.originalname.match(/\.(pdf|doc|txt|jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$/)) { req.fileValidationError = 'Only files are allowed!'; return cb(new Error('Only files are allowed!'), false); } cb(null, true); } }
5. Send File Upload Request
- Include Multer module
require('multer'
) - Also, include a middleware file using
require('../middlewares/upload-middleware')
- Create a method
fileUploadForm
to display file upload form - Even create another method
uploadFile
to send file upload requests.
File Name – upload-controller.js
var multer = require('multer'); var fileUpload= require('../middlewares/upload-middleware'); module.exports={ fileUploadForm:function(req,res){ res.render('upload-form'); }, uploadFile:function(req,res){ var upload = multer({ storage: fileUpload.files.storage(), allowedFile:fileUpload.files.allowedFile }).single('file'); upload(req, res, function (err) { if (err instanceof multer.MulterError) { res.send(err); } else if (err) { res.send(err); }else{ res.render('upload-form'); } }) } }
6. Create a Route File to Upload File
- include a controller file using
require('../controllers/upload-controller')
- Create a route
/upload
with the GET method to display file upload form - Also, Create another route
/upload
with the POST method to upload files. This route will be called when you submit the file upload form.
File Name – upload-route.js
const express = require('express'); const router = express.Router(); const fileUploadController= require('../controllers/upload-controller'); router.get('/upload',fileUploadController.fileUploadForm); router.post('/upload',fileUploadController.uploadFile); module.exports = router;
7. Include the Route File in the app.js
At last, You must load the following file uploading route in the main file app.js
File Name – app.js
var uploadRouter = require('./routes/upload-route'); app.use('/', uploadRouter);
8. Run Node.js App to Upload File
First of all, Start the Node.js server, then enter the following URL in your browser and press Enter.
http://localhost:3000/upload
The above URL displays the file upload form in your browser.
9. My Suggestion
Dear developers, I hope you have understood the above script and you are able to upload files in Node.js express using Multer. Now, you can easily implement another file uploading in Node.js express.
If you have any doubts or questions. You can directly ask me through the below comment box.