Thursday, June 18 2020

How to Integrate File Upload using Multer with Node.js and Express JS

In this tutorial, we discuss about How to Integrate File Upload using Multer with Node.js and Express JS. File upload is a very common operation in any application. In node.js adding a file upload feature using multer package to add a file very easy to app. Here we are going to see file upload operation in two ways.

fileupload-using-multer-with-node-js-express-js

Uploading a File through:

  1. Postman
  2. HTML Form

First, we see the file upload with Multer in Node.js and Express JS using Postman.

Prerequisites:

  1. Express – is a popular framework which is a most common framework used in node.js
  2. Multer – It is a middleware for handling multipart/form-data, which is primarily used for uploading files.
  3. Postman – for testing API.
  4. Embedded Javascript Template – used to implement HTML tags elements such as forms, layouts etc.

Install the Packages:

npm install express --save
npm install path --save
npm install multer --save

Project Setup

Your project setup look like this

project-setup-multer-with-node-js

In app.js file create a server with following contents

// load express
const express = require('express');
const app = express();
app.get('/', (req, res) => {  
   res.send('hello world');
});
app.listen(3000, () => { 
    console.log('Started on port 3000');
});

Now run the file using the below command in the terminal.

node app.js

After this, You can get the server URL http://localhost:4000/  Open the browser and check that URL.

node-js-create-a-server-using-express-js

Adding Multer

Adding multer package in app.js using require() method.

const multer = require('multer');
const upload = multer({dest:'uploads/'}).single("file_image");

In the above code dest option used to store the file in the specified directory. If you omit this file doesn’t written in the disk.

DiskStorage

The disk storage engine gives you full control over storing files to disk. We will create a storage object using the diskStorage() method.

The following code will go in app.js

 var storage = multer.diskStorage({ 
            destination: function (req, file, cb) { 
            
                // Uploads is the Upload_folder_name 
                cb(null, "uploads") 
            }, 
            filename: function (req, file, cb) { 
                cb(null, file.fieldname + "-" + Date.now()+ path.extname(file.originalname)) 
            } 
        });

Here, there are two properties, destination, and filename. They both are functions.

destination: used to allows you to which directory you want to store the uploaded files.

filename: used to determine what the file should be named inside the folder.

null: Don’t want to show any error.

Multer Upload Options

  1. limits – You can also put a limit on the size of the file that is being uploaded with the help of using limits.
  2. fileFilterSet this to a function to control which files should be uploaded and which should be skipped.
const maxSize = 1 * 1000 * 1000; // max 1 MB

var upload = multer({  
            storage: storage, 
            limits: { fileSize: maxSize }, 
            fileFilter: function (req, file, cb){ 
            
                // Set the filetypes, it is optional 
                var filetypes = /jpeg|jpg|png/; 
                var mimetype = filetypes.test(file.mimetype); 
          
                var extname = filetypes.test(path.extname(file.originalname).toLowerCase()); 
                
                if (mimetype && extname) { 
                    return cb(null, true); 
                } 
              
                cb("Error: File upload only supports the " + "following filetypes - " + filetypes); 
              }  
          
        // file_image is the name of file attribute 
        }).single("file_image");  

The following code will go in app.js:

app.post("/imageUpload", (req, res) => {
   upload(req, res, (err) => {
    if(err) {
      res.status(400).send("Something went wrong!");
    }
    res.send(req.file);
  });
});

Run the app.js file and check this URL http://localhost:4000/imageUpload in Postman.

file-upload-using-multer-with-node-js

File Upload Using HTML Form

You need to install ejs package that helps to integrate form in node.js.

npm install ejs --save

Update the following code in app.js

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.set('views',path.join(__dirname,'views'));

Created views directory for html related files such as forms, layouts are inside this folder.

mkdir views

cd views

touch fileupload.ejs

In fileupload.ejs  file inside .views/ directory with following contents

<!DOCTYPE html> 
<html> 
<head> 
    <title>FILE UPLOAD DEMO</title> 
</head> 
 <body> 
    <h1>File Upload Demo</h1> 

    <form action="/imageUpload" 
      enctype="multipart/form-data" method="POST"> 
      
        <span>Upload Profile Picture:</span>   
        <input type="file" name="file_image" required/> <br> 
        <input type="submit" value="submit">  
    </form> 
</body> 
</html> 

In app.js  file update the following contents

app.get('/', function(req, res) {
    res.render('fileupload');
});

To run app.js file in the terminal http://localhost:4000/

file-upload-ejs-with-node-js

Finally app.js file integrated with all codes

// load express
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();

// ejs for html template
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.set('views',path.join(__dirname,'views'));

// Disk storage
var storage = multer.diskStorage({ 
    destination: function (req, file, cb) { 
    
        // Uploads is the Upload_folder_name 
        cb(null, "uploads") 
    }, 
    filename: function (req, file, cb) { 
        cb(null, file.fieldname + "-" + Date.now()+ path.extname(file.originalname)) 
    } 
});

// multer upload options
const maxSize = 1 * 1000 * 1000; // max 1 MB
var upload = multer({  
            storage: storage, 
            limits: { fileSize: maxSize }, 
            fileFilter: function (req, file, cb){ 
            
                // Set the filetypes, it is optional 
                var filetypes = /jpeg|jpg|png/; 
                var mimetype = filetypes.test(file.mimetype); 
          
                var extname = filetypes.test(path.extname(file.originalname).toLowerCase()); 
                
                if (mimetype && extname) { 
                    return cb(null, true); 
                } 
              
                cb("Error: File upload only supports the " + "following filetypes - " + filetypes); 
              }  
          
        // file_image is the name of file attribute 
        }).single("file_image");  

// routing for home page
app.get('/', function(req, res) {
    res.render('fileupload');
});

// routing for file upload
app.post("/imageUpload", (req, res) => {
    upload(req, res, (err) => {
        if(err) {
            res.status(400).send("Something went wrong!");
        }
            res.send(req.file);
    });
});

// create server
app.listen(4000, () => { 
    console.log('Started on port 4000');
});

Building a Restful CRUD API with Node.js Express and MongoDB

How to Make Your App Save and Secure from Security Issues

Share Your Thoughts

phpexpertise

I’m Blogger and Programming Blog, Tutorials, PHP, MySQL, jQuery, Laravel, Wordpress and Codeigniter