Ajax file upload in Node.js

In last tutorial i have explained how to handle file uploads in node.js. That code needs a page refresh in order to upload file which is not a good practice in terms of user experience.

In this tutorial i am going to explain how to develop file uploads using node.js with Ajax. So it won’t need a page refresh at all.

LIVE DEMO DOWNLOAD

Recommended read : File uploads using node.js

Our application :

I am going to develop same application as i have did in last tutorial with some additional code changes which makes it asynchronous or Ajax.

CHANGE LOG
#1 : Handling global variable issue.
#2 : Upgrading to latest version of multer.

So we will use FORMĀ submit and same Express router with multerĀ middleware for handling file upload.

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"
  }
}

Switch to the folder where package file is saved and type

npm install

to install the dependencies.

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
<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" />
      <input type="submit" value="Upload Image" name="submit">
      <span id = "status"></span>
    </form>
  </body>
  <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>
</html>

If you have noticed we are using jquery.form library which allow us to do Ajax form submit. Have a look to JavaScript code.

index.html
<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) {
        $("#status").empty().text(response);
                console.log(response);
            }
    });
        //Very important line, it disable the page refresh.
    return false;
    });    
});
</script>

On Form submit, we will stop the page refresh by returning FALSE and call the API using ajaxSubmit(). 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 code :

Either download the ready made code from Github or save all those files in separate folder and switch to that folder using command prompt.

node Server.js

Visit localhost:3000 to view the app. Open chrome developer console or firebug console in order to see response from server.
run code 1

Output :

output

Conclusion:

Ajax always provides richness to web application. jQuery.form is one of the stable and popular library. Multer takes care of handling multi-part data and provides ease to implementation.

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

14 Comments

  1. Could you kindly demonstrate how to do select and update image immediately without file submit to server ?
    Thanks

  2. ‘return false; ‘ not working and also
    showing error : ‘$(…).ajaxSubmit is not a function’

    Am i using some outdated version or is it deprecated

  3. Hy , thanks for this tuto,
    Please , how use multer without express ( using a new FormData() ) ,
    Thanks

  4. Hi.. Nice Tutorial!! The File Save to the disc system is uploaded without the extension, So can’t be viewed. Any other way to achieve it.

    NOTE: Am using a win-7 for development

  5. Hi .. Nice Tutorial and thanks for that!!
    And when trying out your example, file get saved without extension. So `file.fieldname` can be replaced with `file.originalname` to get the file name with extension

Leave a Reply

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