Express.js File Upload

Express.js File Upload

  • File upload is difficult because of its asynchronous nature and networking approach.
  • It is done using middleware to handle multipart/form data. Middleware are used like multer,connect,body-parser etc.
  • Example to demonstrate file upload in Node.js using middleware 'multer':
  • Create a folder name file uploads and install multer middleware by running command on terminal
 npm install --save multer

In index.html 

    <title>File upload Example by Codersdaily</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: by CodersDaily</h1>  
      <form id="uploadForm" enctype="multipart/form-data" action="/uploadjavatpoint" method="post">  
       <input type="file" name="myfile" /><br/><br/>  
       <input type="submit" value="Upload Image" name="submit"><br/><br/>  
       <span id="status"></span>  

In file app.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.originalname);  
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 2000");  

Run the server by command on terminal

node app.js

Server on port 2000

Uploading file

  • After successful upload You can see file in uploads folder