File Upload in Node.js Server

File Upload in Node.js Server

In this tutorial will learn how to upload any file to the node.js server. File upload in node.js seems tedious due to its async nature and network programming approach. However, it is one of the easiest file upload mechanism I have come across.

Introduction

We will be using node.js + express. We will be using “multer” as middleware. This middleware is designed to handle the multipart/form-data which is primarily used to upload files.

Start node project

Let us assume that you know how to setup node.js express project or you can learn from my previous article here.

package.json

{
  "name": "nodejs-fileupload",
  "main": "server.js",
  "dependencies": {
    "express": "4.13.3",
    "multer": "1.1.0"
  }
}

Installing the dependency. Now copy and paste above package.json save and run following command in terminal :

npm install

Now, go to the server.js and copy the following code :

var express =   require("express");
var multer  =   require('multer');
var app     =   express();

var storage =   multer.diskStorage({
  // file upload destination
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});

var upload = multer({ storage : storage}).single('avatar');

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

app.post('/api/avatar',function(req,res){
    upload(req,res,function(err) {

      // req.file is the `avatar` file
      // req.body will hold the text fields, if there were any

        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});

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

index.html

<form id        =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "/api/avatar"
     method    =  "post"
>
<input type="file" name="avatar" />
<input type="submit" value="Upload Image" name="submit">
</form>

Copy and save the above code and run the node.js server by typing following command :

node server.js

Multer Storage options:

The following are the options that can be passed to Multer.

KeyDescription
dest or storageWhere to store the files
fileFilterFunction to control which files are accepted
limitsLimits of the uploaded data
preservePathKeep the full path of files instead of just the base name

Following is the snippet where you can see storage is defined. In multer.diskStorage() we have to set the file storage destination and filename can be changed as shown.

var storage =   multer.diskStorage({
  // file upload destination
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    // custom function to change filename
    var fileExtension = file.originalname.split('.');
    callback(null, `${file.fieldname}-${Date.now()}.${fileExtension[fileExtension.length - 1]}`);
  }
});

Each file contains the following information :

KeyDescriptionNote
fieldnameField name specified in the form
originalnameName of the file on the user’s computer
encodingEncoding type of the file
mimetypeMime type of the file
sizeSize of the file in bytes
destinationThe folder to which the file has been savedDiskStorage
filenameThe name of the file within the destinationDiskStorage
pathThe full path to the uploaded fileDiskStorage
bufferA Buffer of the entire fileMemoryStorage

Conclusion:

Multer is very nice middleware created by Express community. It really helps us to quickly develop critical code like File uploads in Node.js easily. I hope you find this tutorial helpful.

Cheers!! Happy Coding.

Adam Brown
Please follow and like us:

Leave a Comment