File uploads using Node.js

File upload in node.js seems tedious due to it’s async nature and network programming approach. However it is one of the easiest file upload mechanism i have seen yet.

Prerequisites: You should know how to handle router in Express.

LIVE DEMO DOWNLOAD

How to perform file upload?

I am going to use express framework and middleware called “multer”. This middleware is designed for handling the multipart/form-data.

In front-end script, we will set the “target” parameter of FORM to our router. for.eg  /upload/picture and in app.get(‘/upload/picture’, …) we will be able to handle our file. Let’s see how.

Our project:

This project is simple. We will have simple express web server which does the task of routing and other stuff. Multer will take care of the file handling and HTML for handling form input.

change log
#1: Fixing global variable issue.
#2: Upgrading to multer v 1.1.0.
package.json
{
  "name": "file_upload",
  "version": "0.0.1",
  "dependencies": {
    "express": "4.13.3",
    "multer": "1.1.0"
  },
  "devDependencies": {
    "should": "~7.1.0",
    "mocha": "~2.3.3",
    "supertest": "~1.1.0"
  }
}

Installing dependency:

Save the package.json in folder and type

npm install

to install the required stuff.

This code is updated with latest version of Multer.

Server.js
var express =   require("express");
var multer  =   require('multer');
var app         =   express();
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}).single('userPhoto');

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

app.post('/api/photo',function(req,res){
    upload(req,res,function(err) {
        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/photo"
     method    =  "post"
>
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
</form>

Running project:

Copy code and save them in folder. Type

node Server.js

to run the project. Visit localhost:3000 to view the app. Select the file and check the uploads folder. Your file must be present there!

Explanation :

In our Server.js file, we have configured multer. We have made custom middle-ware function to choose the storage engine which is Disk because we want files to store in disk and appending the file name with current date just to keep the uniqueness of files.

After completing upload , req.files variable holds following array of information.

{
  userPhoto:
  {
     fieldname: 'userPhoto',
     originalname: 'banner.png',
     name: 'banner1415699779303.png',
     encoding: '7bit',
     mimetype: 'image/png',
     path: 'uploads&#92;banner1415699779303.png',
     extension: 'png',
     size: 11800,
     truncated: false,
     buffer: null
 }
}

We are initializing the multer in our /api/photo/ router and in callback we are receiving the error. If there is no error that means file is uploaded.

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

In HTML form you must mention enctype=”multipart/form-data” else multer will not work.

Performing file validation:

To perform validation on Server end, multer provides limits array parameter which have following parameters. ( Reference: Github official page. )

  • fieldNameSize – integer – Max field name size (Default: 100 bytes)
  • fieldSize – integer – Max field value size (Default: 1MB)
  • fields – integer – Max number of non-file fields (Default: Infinity)
  • fileSize – integer – For multipart forms, the max file size (in bytes) (Default: Infinity)
  • files – integer – For multipart forms, the max number of file fields (Default: Infinity)
  • parts – integer – For multipart forms, the max number of parts (fields + files) (Default: Infinity)
  • headerPairs – integer – For multipart forms, the max number of header key=>value pairs to parse Default: 2000 (same as node’s http).

You can define it like this

limits: {
  fieldNameSize: 100,
  files: 2,
  fields: 5
}

In our code.

var upload = multer({ storage : storage},{limits : {fieldNameSize : 10}}).single('userPhoto');

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.

Further reading:

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

171 Comments

  1. This actually came at a perfect time for me. Currently creating an Angular, Node, Express app and file uploading was the last piece of the puzzle. Thanks!

  2. Hi, thanks a lot for this post, but I’m hoping that you guys can answer a question for me, I’m currently using multer, but a need a way to upload files to different directories. For example images to ‘uploads/img’, pdf files to ‘uploads/pdf’ and so on. Thanks again.

    1. Hi Juan,
      By default this feature is not available. You need to create multiple instance of multer for different file types and in each instance define the destination. Hope this snippet trigger the idea.

      var multer  = require('multer');

      var mwMulter1 = multer({ dest: './uploads1/' });

      app.post('/files1', mwMulter1, function(req, res) {
          // check req.files for your files
      });

      var mwMulter2 = multer({ dest: './uploads2/' });

      app.post('/files2', mwMulter2, function(req, res) {
          // check req.files for your files
      });
  3. Hi,
    I’m getting this error:
    TypeError: path must be absolute or specify root to res.sendFile

    I think I didn’t get what are the parameters of sendFile function

  4. hello thanks for your tutorial,but now I have some problem.
    I can run when I use this server.
    but if I add to my server I got this Error.
    Error : Request aborted at IncomingMessage.onReqAbortd ……

  5. Thanks for the valuable post!

    However I suggest you emphasize that having a name attribute for the input HTML element is compulsory for the multer to work.

    I seldom used name in HTML and skipped it now too. Then multer just did not work and I was dredging all over for the fix till I found a stackoverflow tip to just add a name!!

  6. Hello,

    Thanks a lot for this great tuto.
    I’ve got this message :
    express deprecated res.sendfile: Use res.sendFile instead

    And, when using this :
    app.use(multer({ dest: ‘./uploads/’,
    rename: function (fieldname, filename) {
    return filename+Date.now();
    },
    limits: {
    fieldNameSize: 100,
    files: 2,
    fields: 5
    }
    }));

    I’ve got this error on line 20 :

    onFileUploadStart: function (file) {
    ^
    SyntaxError: Unexpected token (

    Could you help me please ?

    Thanks again for the tuto,

    ANDRE_Ani

    1. You are using one extra

      app.use(multer({ dest: ‘./uploads/’,
      rename: function (fieldname, filename) {
      return filename+Date.now();
      },
      limits: {
      fieldNameSize: 100,
      files: 2,
      fields: 5
      }
      });
      1. Thanks a lot, I’ll test this.
        Thanks again for this great tuto, very usefull for a beginner like me.

  7. hi..thanks for this tutorial..it works perfect..may i know how to display image that i already upload based on the image name saved in the database?thanks in advance..

  8. Me again, sorry.
    If I use this :

    app.use(multer({ dest: ‘./uploads/’, rename: function (fieldname, filename) {
    return filename+Date.now();
    },
    limits: {
    fieldNameSize: 100,
    files: 2,
    fields: 5
    }
    });

    onFileUploadStart: function (file) {
    console.log(file.originalname + ‘ is starting …’)
    },
    onFileUploadComplete: function (file) {
    console.log(file.fieldname + ‘ uploaded to ‘ + file.path)
    done=true;
    }
    }));

    I have this error :

    app.js:18
    });
    ^
    SyntaxError: Unexpected token ;

    And for the deprecated, I have this :

    TypeError: path must be absolute or specify root to res.sendFile

    Sorry again, I’m a beginner…

      1. I download and run the code from Github, and it seems good, it’s the result :

        Working on port 3000
        express deprecated res.sendfile: Use res.sendFile instead Server.js:20:11
        live.png is starting …
        userPhoto uploaded to uploads/live1432709554651.png
        { userPhoto:
        { fieldname: ‘userPhoto’,
        originalname: ‘live.png’,
        name: ‘live1432709554651.png’,
        encoding: ‘7bit’,
        mimetype: ‘image/png’,
        path: ‘uploads/live1432709554651.png’,
        extension: ‘png’,
        size: 14153,
        truncated: false,
        buffer: null } }

        And with the modified code for file validation :

        var express = require(“express”);
        var multer = require(‘multer’);
        var app = express();
        var done = false;

        app.use(multer({ dest: ‘./uploads/’,
        rename: function (fieldname, filename) {
        return filename+Date.now();
        },
        limits: {
        fieldNameSize: 100,
        files: 2,
        fields: 5
        }
        }));
        onFileUploadStart: function (file) {
        console.log(file.originalname + ‘ is starting …’)
        },
        onFileUploadComplete: function (file) {
        console.log(file.fieldname + ‘ uploaded to ‘ + file.path)
        done=true;
        }
        }));

        app.get(‘/’,function(req,res){
        res.sendfile(“index.html”);
        });

        app.post(‘/api/photo’,function(req,res){
        if(done==true){
        console.log(req.files);
        res.end(“File uploaded.”);
        }
        });

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

        I have this :

        onFileUploadStart: function (file) {
        ^
        SyntaxError: Unexpected token (

        1. Oh you are using function outside of scope. Run this

          app.use(multer({ dest: './uploads/',
           rename: function (fieldname, filename) {
              return filename+Date.now();
            },
          limits: {
            fieldNameSize: 100,
            files: 2,
            fields: 5
          },
          onFileUploadStart: function (file) {
            console.log(file.originalname + ' is starting ...')
          },
          onFileUploadComplete: function (file) {
            console.log(file.fieldname + ' uploaded to  ' + file.path)
            done=true;
          }
          }));
  9. my English is bad. If use app.use(express.bodyParser()) and before insert app.use(multer({/*…*/})), you example dont work. Or at the beginning
    insert app.use(multer({/*…*/})) and before app.use(express.bodyParser()), how to close connection with client.

  10. Hello,

    I want to thank you for this tutorial. I only have a simple question. After uploading the file, how can I redirect to another html page?

    Thanks

  11. Hi man. Thanks for this tuto, it’s great. However it seems the form uploads the file even if you don’t call /api/photo. I mean, if you change the action of the form to anything, like “http://myserver”, it will upload the file anyway. So it’s not respecting the routes. Any idea why this is happening? Thanks!

  12. Nice tutorial….,
    I created multiple instance of multer for different file types and each instance defined specific destination but I am also using json web tokens for authentication. In this case i am getting TypeError: Cannot read property ‘token’ of undefined. Is it possible to use both different multers and json webtokens? but Whenever upload all files into single destination i didn’t get any error.

  13. How do I upload a file from an application (e,g, from a perl script or java script) and not through a browser but using this node server. Appreciate any pointers in this regard.

  14. In addition to the browser form upload, I would like to upload files through an application (like Perlscript or node javascript) and using the same server. Appreciate any pointers in this regard.

    1. What would be your source ? From where you wanna upload file ? If i get it right its server to server then you don’t need upload. Just move them from one location to another.

      1. Of course it is from client to the server. Client will run an application and that will make a post to server and transfer/upload a file.

  15. var multer = require(‘multer’);

    var mwMulter1 = multer({ dest: ‘./uploads1/’ });

    app.post(‘/files1’, mwMulter1, function(req, res) {
    // check req.files for your files
    });

    var mwMulter2 = multer({ dest: ‘./uploads2/’ });

    app.post(‘/files2’, mwMulter2, function(req, res) {
    // check req.files for your files
    });

    I am using this code to upload images into different folders it is working fine but i am not getting post data it simply display undefined format. the code look like this.

    app.post(‘/test’, function(req, res){
    var name = req.body.name;
    console.log(“Name is — “+name);
    res.json(“name sent to server”);

  16. First of all, thanks for your tutorial. But I’m trying to use it and it doesn’t work. In my case, I don’t have the upload form in the index page, but in a secondary page (located in a directory, ‘partials/upload.jade’, I use Jade for make my pages) I also use AngularJS… Should it be a problem? I follow all your tutorial step by step, the only difference is what I have mentioned.

    Thank you in advance.

      1. Of course, here is my main Node.js file (in your case the “server.js”):

        https://github.com/lousan92/genealogical-tree/blob/master/app.js

        And that’s the Jade file which contains the form:

        https://github.com/lousan92/genealogical-tree/blob/master/views/partials/upload.jade

        There’s also a problem: if I add “method=’POST'” to the form, it appears a message saying me “Cannot GET /api/uploadFile?”. If not, the browser doesn’t charge anything.

        Another thing to say is that I have my APIs in a separate page, but once again it shouldn’t be a problem if I have the upload API with a direct callback function in the main file, am I wrong? Because I need the “done” boolean I guess.

        Thank you again and sorry for the double post, I thought that it wasn’t sent!

          1. It still doesn’t work. But now I’ve discovered that any of my POST APIs work when I configure Multer, and I don’t know why (I have a form to add data to the database, and in normal conditions it works, but when I add your code to configure Multer I can’t do it).

          2. Sorry, now the other APIs seem to work fine with Multer. But the “upload” one continues without working, following your steps.

            (And sorry again for double posting, I used the inline comments thinking that it was the reply button)

          3. Hi again, don’t worry about that: I’ve finally been able to make the code work (if you ask me, I don’t know how :P). Thanks again 🙂

  17. Nice tutorial, but I’m trying to follow your steps and I’m not able to upload files. When I click the Upload button, the browser tells me “Cannot GET /api/uploadFile?”. I have more APIs in my project, and all of them work without problems (I have tried with another ones in that form and they work). What could happen? Multer is configured as you did and I’ve put the “api/uploadFile” line (the name I’ve used) in the same way as you.

    Thank you in advance.

  18. TypeError: app.use() requires middleware functions
    at EventEmitter.use (D:UsersFINCHDesktopNodenode_modulesexpresslibap

    I copied your exact code. The error is pointing to this line:
    app.use(multer({ dest: ‘./uploads/’,……

  19. It still doesn’t work. But now I’ve discovered that any of my POST APIs work when I configure Multer, and I don’t know why (I have a form to add data to the database, and in normal conditions it works, but when I add your code to configure Multer I can’t do it).

  20. Looks good but just cannot make it work, this is ubuntu 12.04, installed node 0.12.7, express 4.13.1.

    made 1 change to app.use: added single().
    app.use(multer({ dest: ‘./uploads/’,
    rename: function (fieldname, filename) {
    return filename+Date.now();
    },
    onFileUploadStart: function (file) {
    console.log(file.originalname + ‘ is starting …’)
    },
    onFileUploadComplete: function (file) {
    console.log(file.fieldname + ‘ uploaded to ‘ + file.path)
    done=true;
    }
    }).single(‘userPhoto’));

    i do see file gets uploaded successfully, it’s a picture, opens fine.

    BUT never hits onFileUploadStart, onFileUploadComplete. Webpage just keeps on waiting and never hits if(done==true)

    Any help appreciated.

  21. Hi, I am trying to insert image into mongodb using angularjs and nodejs using mongojs module, can any one suggest me how can I do this thing????

  22. Hi ! Thanks for this tutorial. I have a question to ask you =)
    I would want to upload a form containing a video file and parameters, such as :
    “formData.append(‘media_format’, extension);
    formData.append(‘media’, blob);
    formData.append(‘mediaid’, id);”
    But I can’t seem to find where in your code I could put those infos. Is this automatically taken care of when you send the form from your .html client file to your .js server file ?

  23. Hi,

    thanks for great tutorial. Got everything working with one exception.
    I’m printing req.files with console.log and it’s returning only { userPhoto:
    and nothing else from the array. If I try to print directly other item from the array, it returns undefined. Any idea why is it doing this?

    Thanks again.

  24. Thanks for the tutorial, it really helped. I have a question, hopefully you can help me out.

    From what I’m seeing, ‘done’ is a global variable, right? If you have multiple users uploading files at the same time, will the variable be set to true as soon as the first upload finishes? Wouldn’t that affect the other users?

    Or does onFileUploadComplete emit just to the user that’s uploading?

  25. i do see file gets uploaded successfully,
    BUT never hits onFileUploadStart, onFileUploadComplete. Webpage just keeps on waiting and never hits if(done==true)
    & file extension is also missing
    Any help appreciated.

    1. Hey, i think i got where you are confused with. done == true is hitting and that is why console is printing req.files object. About res.end, you can see that in browser console cause we are not rendering our pages from Node script. We used res.sendFile to send HTML page to browser.

  26. for this line,

    app.post(‘/files1’, mwMulter1, function(req, res) {
    });

    im getting error like this

    Route.post() requires callback functions but got a [object Object]

  27. Hi,

    for the line
    app.post(‘/files1’, mwMulter1, function(req, res) {
    // check req.files for your files
    });

    im getting error like this.
    Route.post() requires callback functions but got a [object Object]

    can you please help me.

          1. I have done like this

            var multer = require(‘multer’);

            var mwMulter1 = multer({ dest: ‘./uploads1/’ });

            app.post(‘/files1’, mwMulter1, function(req, res) {
            // check req.files for your files
            });

  28. Hi,

    for the line

    app.post(‘/files1’, mwMulter1, function(req, res) {
    // check req.files for your files
    });

    as you have suggested for Juan Irizar,

    its throwing error like this,

    Route.post() requires callback functions but got a [object Object].

    Can you please help?

  29. Thank u, for this helpful post. But, can we upload the images in using this in drag-and-drop manner also..? Please confirm..

  30. Thanks for the tutorial, it really helped. I have a question, hopefully you can help me out.
    my question is how to create file uploading in node js but one think is there register user are id used to folder name to create server site.there folder name is updeted user id for the folder.plz help me.

      1. ya sir i need new folder created in each user id to save in the mongoose in mongodb to fech this id and create folder in node.js server side.
        i am created new registration form to used in restful api in this registration are complited it will genrat on id this id are fech in server side and newly create folder in server.
        ex. user/uploads/123(id fech in mongodb)
        user/uploads/124
        plz help me…

  31. this is not working

    app.use(multer({dest:’./uploads/’}).single(‘photo’));

    .single(‘photo’)); is missing…

    also it gives typeerror bcoz upload is not function

          1. Now I am getting below

            Error uploading file.Error: ENOENT, open ‘folderpath\userPhoto-1450888354667’

  32. Hello does multer or any of the other Node.js upload libraries have an overwrite option that will prevent the renaming behavior and just overwrite the file if it already exists. Thanks

    1. Nope.

      But you can write function which do that before uploading a file into system. Use “FS” module function to check the existence and if exist delete that.

    2. I know this is late, but for anyone else reading this, I’m finding the default action by multer IS to overwrite the file if it already exists.

  33. Hey How do I know where the file was uploaded?like if I want to see the image uploaded, what url willl i have to go to? Does it save the image to the “uploads” folder you created?

  34. hi, how to check the user validation before file get uploaded. the file should upload once the user is valid.

  35. Hi!

    nice article! I think there is a minor error on the limit example. Where it says:
    var upload = multer({ storage : storage},{limits : {fieldNameSize : 10}}).single(‘userPhoto’);
    I think it should say:
    var upload = multer({ storage : storage, limits : {fieldNameSize : 10}}).single(‘userPhoto’);
    Otherwise the limits are not taken into consideration.

    Regards,
    V.

    1. Hi,

      After you submit the file successfully to node server, you need to return back the response with file path which you can access in req.files.path variable. And in UI, upon recieving success response, show that path using tag. That’s it.

    1. Hi,

      After you submit the file successfully to node server, you need to return back the response with file path which you can access in req.files.path variable. And in UI, upon recieving success response, show that path using tag. That’s it.

  36. hello sahid, i have followed your tutorial, but i changed only the destination specify function to this var upload = multer({dest: __base +’/public/uploads’}).single(‘userPhoto’); but after uploading an image, the file type uploaded was “File” with the name like 887710ec416ef7f448905f8a0a7509a0. what is going on with my code?
    var multer = require(‘multer’);
    var upload = multer({dest: __base +’/public/uploads’}).single(‘userPhoto’);
    app.get(‘/uploads’,function(req,res){
    res.sendFile(__base +”/public/views/index.html”);
    });
    app.post(‘/upload’, function(req, res){
    upload(req, res, function(err){
    if (err) {return res.end(“error uploading file.”);}
    // res.send(req.files);
    res.end(“file uploaded”);
    })
    })

  37. Hey shahid,
    Nice work there.
    I wonder you could guide me how to handle errors which come when file size is exceeded and also when the format is incorrect. I also want to send an error response to client when the above errors occur. I knew my way around before multer 1.1.0. Please guide me how to do this in multer 1.1.0. I can’t seem to find a way out.
    Thanks.

  38. Hey shahid,
    Nice work there.
    I wonder you could guide me how to handle errors which come when file size is exceeded and also when the format is incorrect. I knew my way around before multer 1.1.0. Please guide me how to do this in multer 1.1.0. I can’t seem to find a way out.
    Thanks

    1. Replied on your email.

      Here is snippet for everyone looking out for same.

      var upload = multer(
        {
          storage : storage,
          fileFilter : function(req, file, callback) {
              var fileType = ['xls','xlsx'];
              if (fileType.indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                  return callback(new Error('Wrong extension type'));
              }
              callback(null, true);
          }
        }).single('userPhoto');
  39. Hey Shahid,
    Kudos to you and the codeforgeek for doing such an awesome job to help newbies like us out.
    I did as you told but have run into a new problem.
    The limits option does not seem to work.
    I have handled the error in the function inside the route(‘/dp’ is my action for uploads)
    When I upload a large file, the response “SIZ” is send after a long time proportional to the size of the file being uploaded indicating that upload is not being aborted and limits is failing. Am I missing something here?
    My upload object definiton.
    var maxSize = 1 * 1024 * 1024;
    var upload = multer({ dest: ‘./bin/uploads/’,
    limits: {
    fileSize: maxSize,
    files: 1
    },

    filename: function (req, file, callback) {
    callback(null, file.fieldname + ‘-‘ + Date.now());
    }

    fileFilter: function (req, file, cb) {

    var ext = path.extname(file.originalname);
    if (ext !== ‘.jpg’ && ext !== ‘.png’ && ext!== ‘.gif’ && ext!== ‘.bmp’ ) {
    console.log(“File extension violated”);
    // throw error;
    return cb(null, false)
    }

    cb(null, true);
    }

    }).single(‘avatar’)
    My route where upload is being handled.

    app.post(‘/dp’ , function(req ,res){
    upload(req,res,function(err) {

    if(err) {
    console.log(“ERROR multer 1.1.0–>”+err);
    var er_string = String(err);
    console.log(typeof er_string);
    console.log(“er_string “+ er_string)
    if(er_string==”Error: EXT”)
    {
    console.log(“res send err format”);
    res.end(“FRMT”);
    }
    else
    {
    res.end(“SIZ”);
    }

  40. Hello shahid i have problem in node.js.
    I am trying to build an web based application, wherein i take the snapshots of my sites visitors and store them in database( for now its simply a folder ). Server side is controlled with node.js. But the problem is, if i have a image with name say “xyz.png” and if i again try to put a image with the same name in the same folder, latter image gets appended with the previous one (“xyz.png”). The only thing happens is that the size of latter image increases.
    Its happening because i am appending the images to the folder content (because i am using opening it with ‘a’ flag).
    This is the piece of code:
    //fileName is the image name that i want to store
    fs.open(fileName, ‘a’, 0755, function(err, fd) {
    if (err) throw err;

    fs.write(fd, buffer, null, ‘Binary’, function(err, written, buff) {
    fs.close(fd, function() {
    console.log(‘File saved successful!’);
    });
    })
    });
    Is there any other way of doing this thing. As i don’t want to loose my previous content of the folder.

  41. Hi Shahid
    I have problem in node.js while uploading file from html
    i am using express framework for my application
    app.js file

    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}).single(‘userPhoto’);

    app.post(‘/api/photo’,function(req,res){
    upload(req,res,function(err) {
    if(err) {
    return res.end(“Error uploading file.”);
    }
    res.end(“File is uploaded”);
    });
    });

    Html form

    name

    Upload file

  42. Everything works great. But upon uploading. What is get is NOT an image file….
    its a different kind of file. …

  43. Hi, great Application ! Just one question, Is possible to use this application on same port of another application ? I need to use my application that works on port 8888 and this application oh the same port, but when I try, I have a javascript error (TypeError: status is not a function)

  44. var express = require(“express”);
    var multer = require(‘multer’);
    var app = express();
    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
    }).single(‘userPhoto’);

    app.get(‘/’, function (req, res) {
    res.sendFile(__dirname + “/index.htm”);
    });

    app.post(‘/api/photo’, function (req, res) {
    upload(req, res, function (err) {
    if (err) {
    return res.end(“Error uploading file.”);
    }
    res.end(“File is uploaded”);
    });
    });

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

    errors shows that Error uploading file.
    i am beginer please help me to solve that problem…

  45. thank you for the tutorial..
    im making rest api with nodejs.
    and i use this turorial for uploading, but i just want to have the path of the uploaded files stored on mongodb, how to do it? pls help thanks

  46. thank you, for this awesome tutorial!

    can you help me to get the uploaded file path, and stored that in mongodb.
    im using nodejs, express, and monk

  47. hello. im new to nodejs and but express.

    can u tell me how i will get the file i upload, to be displayed in the client side, from mongodb. (im assuming i have to take the path of the files, and put it into the datbase) but i still kinda confuse of that, can u give me the simple tutorial/example?

    nice tutorial u give here btw.Thanks

    1. Sorry for late reply Daniel.

      To answer your question, you can get the uploaded file by storing the path variable present in req.files and return it to client to view the file.

      For. eg :

      Insert value present req.files.userPhoto.path variable in Mongo and return it using GET api or in response of file submit to view it on client 🙂

      1. tahnks for answering the question..

        but, how the client can get to the folder that i stored my files to, my server and the client has different origin. since the req.file.path wil only return ../”folder upload”/”filename”
        how the clinet can use this path to access the files.
        im assuming this has something with express.static(path) ,but i dont really understand, can u explain this ? thankyou

        1. Yes, you are right about express.static().

          You need to add that folder as a static path where your file is getting uploaded and once the client is trying to access that, express will automatically resolve the path.

          Assuming folder is uploads, add this in your app file ( assuming the app is in the main directory and not in the sub directory).

          app.use(express.static(__dirname + './uploads'));

          If above doesn’t work, try using path.

          var path = require('path');

          app.use(express.static(path.join(__dirname,'./uploads')));
  48. Thank you for your great tutorial!

    Your code run very well but the test has some problems, I can’t get req.file when I run the test, its always undefined. Can you somehow help me with this?

  49. Thank You for a great tutorial
    I am still new to node and express,The file uploads work great,however I wanted to know how to get the files to display on my client side

      1. Hello,
        I’m a beginner at this and I have the same problem. I’m trying to figure it out but I’m not getting it right. I was wondering if you have the code for this somewhere?
        Thank you in advance 🙂

  50. Thank you for the tutorial, Could you explain if I can use multer for below scenario and if Yes, where should i specify destination host name and port?
    If I want to upload a file from my machine to a different machine where the application is hosted(server), will I be able to do it using multer. I mean I will host a web application on machine one which serves as server and i will access it through the browser of machine 2 which is client. I will upload a file from machine 2 , but it should get uploaded to the server(machine 1).

  51. Hi sir,

    I am beginner in node js, i run the same code what you have given. But i am getting error as below

    TypeError: status is not a function
    [Break On This Error]

    status(‘Error: ‘ + xhr.status);

    please tell me hoe to clear this

      1. i installed node js in my pc (ubuntu 10.04LTS) and i copied codes from here and i was trying to access it from browser.

  52. Hi , Please help me here …….I want to upload diffrent extension files like .txt or excel….. and give path of directory at run time where i hv to upload that file….. can you plz help me …plz comment as soon as possible

  53. Hi ,
    Can we upload files from the local to the server using the https protocol also?
    Because I am not able to uploads files in https but the same works in http.

    Please help.
    Thanks in advance

  54. Thanks for this nice post on uploading files in express js.
    But, a question that i faced, is that if I use other input fields along with file field my file is uploaded but the other input data from the form can not be retrieved, It is showing undefined. What is the problem, Can you please answer?

  55. I want to downloaded uploaded file by browser.
    How I can do it, help me please?

    app.get(‘/’,function(req,res){
    res.sendFile(__dirname + “/index.html”);
    });

    P.S. Thank you it’s very cool example!

  56. This tutorial works great on my local machine. I’m trying to get it to work on my server. I get all the data back with no errors when I upload but the files don’t actually store. Is there a setting in nginx config that I’m missing?

  57. Hi thanks for this tutorial. how to upload .sh (ex: test.sh) files and run/execute those in back end, any body help me please…as soon as possible.

      1. I tried, but its not executing completely and not showing any error.

        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(‘use’,2);

        app.get(‘/’,function(req,res){
        res.sendFile(__dirname + “/index.html”);
        });

        //script execution testing
        var sys = require(‘sys’);
        var exec = require(‘child_process’).exec;

        function puts(error, stdout, stderr) { sys.puts(stdout) }
        exec(“/root/test.sh”, puts);

        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”);
        });

        This is what i am using(server.js), in above code i am giving filename along with path (/root/test.sh) what i am going to upload from browser. How to avoid this and make it general one.

        Thanks in advance

    1. and also the express version is “^4.3.0”
      and should version is “^5.2.0”
      and supertest version is “^0.9.0”
      will it work with this version or i need to upgrade them all?

  58. I am getting an Error- Error Uploading File
    I have simply copied your code if server.js and index.html I am newbie to node.js help me

      1. I have installed all the dependencies that is express and multer but still it was not working
        do I need to make a file or something like that

  59. Thanks so much for your tutorial! There were some oddities, going through it, but in the end I was able to figure everything out that I wanted. I whipped up a system that restricts by file type and size, and checks for a file of the same name before writing to disk. If it’s there, it renames it. Here’s my code for anyone interested (and yes, I realize my renamePng function is redundant.):

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

    var renamePng = function(incomingName) {
        return incomingName.replace(/\..*/i, '') + '.png';
    }
    var storage =   multer.diskStorage({
      destination: function (req, file, callback) {
        callback(null, './uploads');
      },
      filename: function (req, file, callback) {
        var finalName = renamePng(file.originalname);
        fs.open('./uploads/' + finalName, 'r', (err, fd) =&gt; {
            if (err) {
                console.error('Uploading new file: ' + finalName);
                callback(null, finalName);
            } else { // file exists, use generated name
                finalName = finalName.replace('.png', '-COPY-' + Date.now() + '.png');
                console.error('File already exists. Using new name: ' + finalName);
                callback(null, finalName);
            }
        });
      }
    });
    var upload = multer({
            storage : storage,
            fileFilter : function(req, file, callback) {
                var fileType = ['png'];
                if (fileType.indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                    return callback(new Error('Wrong extension type'));
                }
                callback(null, true);
            },
            limits :  {
                fieldNameSize : 50,
                files: 1,
                fields: 1,
                fileSize: 350000
            }
        }).single('userPhoto');

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

    app.post('/api/photo',function(req,res){
        upload(req,res,function(err) {
            if(err) {
                return res.end("Error uploading file. " + err);
            }
            res.end("File is uploaded: " + renamePng(req.file.filename));
        });
    });

    app.listen(3030,function(){
        console.log("Working on port 3030");
    });
  60. Thanks for the tutorial, it’s really helpful.

    I still have a question: I’m uploading an image and I get it without an extension, so when I try to open it with a double click, I’m getting some weird characters. I also tried to open in in a browser using html but I’m still getting a broken image.

    Can someone help me, please?
    Thanks!

  61. Hi,
    How can i access the file name inside my app.post().
    I want to access the file name and store it in db so how can i get the files name ?? I need the filename that the multer used not the name by which user uploaded.

Leave a Reply

Your email address will not be published. Required fields are marked *