File upload is a common feature that almost every website needs. To perform uploading operation in ExpressJS we have middleware known as Multer. So in this tutorial, we will go step by step on how to handle single and multiple files uploads with ExpressJS.

Topics Cover:

  1. Getting Familiar with Multer.
  2. Setting Our ExpressJS application.
  3. Uploading Files using ‘Multer’

Getting Familiar with Multer.

Multer :

  • Multer is a node.js middleware for handling multipart/form-data and can be used in ExpressJS for uploading files.

Now the first step that we have to follow is installing the ‘npm’ for multer in your project.

$ npm install multer

Setting Our Express.js application.

  • Once we have done with installing multer then we have to install some more packages(body-parser, express,ejs) which we are going to use in our project.

Body-parser

  • It extracts the entire body portion of an incoming request stream and exposes it on ‘req.body’ as something easier to interface with.

Express

  • Express is very popular web framework of node.js so if we are going to work in express.js then we must need to install its package, using ‘npm’.
var express = require('express');
var app=express();
var parser= require('body-parser');
var multer=require('multer');
var path =require('path');
var ejs= require('ejs');
app.listen('3000',function(req,res){ 
 
   console.log("3000 port");
})

Uploading Files using Multer:-

The two important things we need to know while uploading files are :-

  • destination: Indicates where you want to save your files upload
  • filename: Indicates how you want your files named.

In the below Code ./uploads is a Directory Where the Files will be uploaded.

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
})
//init upload
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/uploads'));
app.get('/', function (req, res) {
    res.render('upload');
})
app.post('/upload', function (req, res) {

    var upload = multer({ storage: storage, limits: { fileSize: 100000000 } }).single('myImage');
    // req.file is the `myImage` file
    upload(req, res, function (err) { console.log(res); if (err) { console.log(err); } else { console.log("hello" + storage); res.send("test"); } })
})

EJS

  • This is an ejs file.This will Use to Upload the data through HTML Form.
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>uploads</title>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 <style>
 .butt
 {
padding-bottom: 20px;

 }
 
 </style>
 
</head>
<body>
<div class="container">
<h1>file uploads</h1>

<form action="/upload" method="post"  enctype="multipart/form-data">
       <div class="file-field input-field">
         <div class="btn btn-danger butt">
           <span>File</span>
           <input type="file" name="myImage">
         </div>
         <div class="file-path-wrapper">
           <input class="file-path validate" type="text">
         </div>
       </div>
       <input type="submit" value="submit">
     </form>
          

</div>


       <script
       src="http://code.jquery.com/jquery-3.3.1.js"
       integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
       crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
  
</body>
</html>

Output in console

file:
      { fieldname: 'myImage',
        originalname: 'Lesson3-HTTP Module - Serving Static Files HTML, CSS, Image.mp4',
        encoding: '7bit',
        mimetype: 'video/mp4',
        destination: './uploads',
        filename: 'myImage-1518518886939.mp4',
        path: 'uploads\\myImage-1518518886939.mp4',
        size: 76981769 } },

Learn More: