Multiple File upload with Node.js

Multiple File upload with Node.js

  • 2016-09-15
  • 1957

We have covered Ajax file upload in Node.js but it was for single file at a time. In this tutorial we will learn how to do multiple file uploads using Multer and Express in Node.js.

Our application :

I am going to develop same application as I have done in last tutorial with some additional code changes which makes it multiple file upload.

We are going to use basic FORM submit along with Ajax submit jQuery plugin to make it asynchronous. Here is our package.json file.

package.json

{
  "name": "file_upload",
  "version": "0.0.1",
  "dependencies": {
    "body-parser": "^1.14.2",
    "express": "4.13.3",
    "multer": "1.1.0"
  },
  "devDependencies": {
    "should": "~7.1.0",
    "mocha": "~2.3.3",
    "supertest": "~1.1.0"
  }
}

Run following command to install the dependencies.

npm install

Here is our Server file with multiple file upload support.

Server.js

var express =   require("express");
var bodyParser =    require("body-parser");
var multer  =   require('multer');
var app =   express();
app.use(bodyParser.json());
var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});
var upload = multer({ storage : storage }).array('userPhoto',2);

app.get('/',function(req,res){
      res.sendFile(__dirname + "/index.html");
});

app.post('/api/photo',function(req,res){
    upload(req,res,function(err) {
        //console.log(req.body);
        //console.log(req.files);
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});

app.listen(3000,function(){
    console.log("Working on port 3000");
});

The only line you need to put your focus on is this

var upload = multer({ storage : storage }).array('userPhoto',2);

Here rather than .single() we are using .array(selector,fileLimit) of Multer. Multer will accept array of files limiting to max 2 file at each time. You can of course increase the number as you may need. Rest of the code is same as previous tutorial.

Here is our HTML file.

Index.html

<html>
  <head>
    <title>File upload Node.</title>
  </head>
  <body>
      <form id="uploadForm"
          enctype="multipart/form-data"
          action="/api/photo"
          method="post">
      <input type="file" name="userPhoto" multiple />
      <input type="submit" value="Upload Image" name="submit">
      <input type='text' id='random' name='random'><br>
      <span id = "status"></span>
    </form>
  </body>
</html>

Here is our JavaScript code which we place in same HTML file. You can place it in different file. Put this code below closing tag of BODY.

index.html

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
  <script>
  $(document).ready(function() {
     $('#uploadForm').submit(function() {
        $("#status").empty().text("File is uploading...");
        $(this).ajaxSubmit({
            error: function(xhr) {
          status('Error: ' + xhr.status);
            },
            success: function(response) {
        console.log(response)
            $("#status").empty().text(response);
            }
    });
    return false;
    });    
});
</script>

On Form submit, we will stop the page refresh by returning FALSE and call the API using ajaxSubmit(). You can Add this code in separate file and add it below the jquery.form or copy and paste just below this line.

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>

<script>
------Paste above code ------
</script>

Running the application

To run the application, switch to project directory and type following command.

node Server.js

Running file upload app

Visit localhost:3000 to view the app. Choose multiple file from selection window and see the console.

Selecting multiple files for app

Upload done

Further enhancement

If you want to have different control for file rather than single HTML control then you need to define multiple files control in HTML with same name in order to recognize the Multer that it is array of files. Here is how you can do this. Currently we are using this.

<input type="file" name="userPhoto" multiple/>

You can write same like this.

<input type="file" name="userPhoto"/>
<input type="file" name="userPhoto"/>

There is no change in back-end code required for above change.

Conclusion

Multer is one of the easy node module you can use with Express for file upload. It allows you to add various validation and support single as well as multiple file uploads.

LIVE DEMO

DOWNLOAD

Suggest

Build an Amazon clone: Nodejs + MongoDB + Stripe Payment

Angular 2 and NodeJS - The Practical Guide to MEAN Stack 2.0

Intro To iOS Backend Development: Image Uploads

Hapi.js Tutorials - Go From Beginner To Advanced!

JavaScript Tutorials: Understanding the Weird Parts