Express FileUpload

File upload is done using multipart form data. We need to use middleware to upload files using nodejs. There are many such modules. One of them is multer.

Lets create a html file “index.html” with below code.
    <title>File upload</title>  
  <script src=""></script>  
  <script src=""></script>  
  $(document).ready(function() {  
     $('#uploadForm').submit(function() {  
         $("#status").empty().text("File is uploading...");  
            error: function(xhr) {  
                    status('Error: ' + xhr.status);  
            success: function(response) {  
    return false;  
      <h1>Express.js File Upload</h1>  
      <form id="uploadForm" enctype="multipart/form-data" action="/upload" method="post">  
       <input type="file" name="myfile" <br/><br/>  
       <input type="submit" value="Upload Image" name="submit"><br/><br/>  
       <span id="status"></span>  

Above code has a form with file upload and submit button. When a file is uploaded and submitted, the javascript code listing to form submit will perform the task. Initially it will set the status msg to file uploading and update the status to file uploaded or error based on the api response.

Lets modify our server.js as below.
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.originalname);  
});  // to set the destination folder in server.

var upload = multer({ storage : storage}).single('myfile');  
      res.sendFile(__dirname + "/index.html");  
    upload(req,res,function(err) {  
        if(err) {  
            return res.end("Error uploading file.");  
        res.end("File is uploaded successfully!");  
    console.log("Server is running on port 8080");  

Here we use multer for file uploading. Multer.diskstorage is used to set the destination folder and that all the multer takes care of the rest.

Below screen shot shows the output of above code.


Below screen shot shows the output on the browser. We need to choose the file file and click file upload.


Below screen shot shows the output on the browser. (Post uploading a file)


Below screenshot shows the uploaded file in the directory.


Subscribe Now