• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to secondary sidebar

CodingStatus

- Level Up Your Status with Coding Expertise!

  • Tutorials
    • React Js Tutorials
    • JavaScript Tutorials
    • PHP Tutorials
    • HTML Tutorials
    • SQL Tutorials
    • Laravel Tutorials
  • Snippets
    • React Js Code Snippets
    • Ajax Code Snippets
    • Node.js Code Snippets
    • JavaScript Code Snippets
    • jQuery Code Snippets
    • SQL Code Snippets
  • Programs
    • PHP Program
    • Python Programs
    • Java Programs
  • How To
    • React Js How To
    • Node Js How To
    • Ajax How To
    • PHP How To
    • jQuery How To
    • JavaScript How to
  • Scripts
    • PHP Script
    • Js Script
    • React Js Script
    • JQuery Script
  • Projects
    • PHP Project
  • Interview Questions
  • Guide
  • API Integration
  • Installation

Node.js File Upload Using Express Multer

October 1, 2021 By Md Nurullah

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.

node.js file upload

Table of Contents

  • How to Upload File Using Node.js & Express
    • 1. Install Express Application
    • 2. Install Express Multer
    • 3. Create File Upload Form
    • 4. Upload File to the Folder
    • 5. Send File Upload Request
    • 6. Create a Route File to Upload File
    • 7. Include the Route File in the app.js
    • 8. Run Node.js App to Upload File
    • 9. My Suggestion

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 the middlewares
  • Declare image folder path in the code cb(null, 'image_folder_path'). Here public/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.

 

Filed Under: Node.js Code Snippets, Uncategorized

Hello Developer, Welcome to my Blog. I'm Md Nurullah, a software engineer with 5+ years in full-stack web development. As the founder of CodingStatus.com, I'm passionate about sharing coding knowledge and collaborating for a brighter future. Let's connect and code together!

Primary Sidebar

Secondary Sidebar

Node.js Code Snippets,
  • Upload Multiple Files Using Multer in Node.js and Express
  • Node.js Send Email – Sending mail using Nodemailer
  • Fetch data from MongoDB Using Mongoose and Node.js Express
  • Node.js Form Validation with an Example
  • Node.js MySQL CRUD Operation with Example
  • Create Registration and Login Form in Node.js & MySQL
  • Node.js MySQL Connection Step By Step
  • MongoDB CRUD Operations Using Node.js Express and Mongoose
  • Connect MongoDB with Node.js Using Mongoose
  • Express MVC Structure – Model, View and Controller
  • Home
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • Sitemap
  • Contact Us

Copyright © 2023 CodingStatus - All Rights Reserved