Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

Express.js File Upload


In Express.js, file upload is slightly difficult because of its asynchronous nature and networking approach.

It can be done by using middleware to handle multipart/form data. There are many middleware that can be used like multer, connect, body-parser etc.

Let’s take an example to demonstrate file upload in Node.js. Here, we are using the middleware ‘multer’.

Create a folder “jtp file upload” having the following files:

expressjs-fileupload1

uploads: It is an empty folder i.e. created to store the uploaded images.

package: It is JSON file, having the following data:

File: package.json

  1. {
  2.   “name”: “file_upload”,
  3.   “version”: “0.0.1”,
  4.   “dependencies”: {
  5.     “express”: “4.13.3”,
  6.     “multer”: “1.1.0”
  7.   },
  8.   “devDependencies”: {
  9.     “should”: “~7.1.0”,
  10.     “mocha”: “~2.3.3”,
  11.     “supertest”: “~1.1.0”
  12.   }
  13. }

File: index.html

  1. <html>
  2.   <head>
  3.     <title>File upload in Node.js by Kreationnext</title>
  4.  <script src=“http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js”></script>
  5.   <script src=“http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js”></script>
  6.   <script>
  7.   $(document).ready(function() {
  8.      $(‘#uploadForm’).submit(function() {
  9.          $(“#status”).empty().text(“File is uploading…”);
  10.         $(this).ajaxSubmit({
  11.             error: function(xhr) {
  12.                     status(‘Error: ‘ + xhr.status);
  13.             },
  14.             success: function(response) {
  15.                     console.log(response)
  16.                     $(“#status”).empty().text(response);
  17.             }
  18.     });
  19.     return false;
  20.     });
  21. });
  22.   </script>
  23.   </head>
  24.   <body>
  25.       <h1>Express.js File Upload: by Kreationnext</h1>
  26.       <form id=“uploadForm” enctype=“multipart/form-data” action=“/uploadKreationnext method=“post”>
  27.        <input type=“file” name=“myfile” /><br/><br/>
  28.        <input type=“submit” value=“Upload Image” name=“submit”><br/><br/>
  29.        <span id=“status”></span>
  30.       </form>
  31.   </body>
  32. </html>

File: server.js

  1. var express =   require(“express”);
  2. var multer  =   require(‘multer’);
  3. var app =   express();
  4. var storage =   multer.diskStorage({
  5.   destination: function (req, file, callback) {
  6.     callback(null‘./uploads’);
  7.   },
  8.   filename: function (req, file, callback) {
  9.     callback(null, file.originalname);
  10.   }
  11. });
  12. var upload = multer({ storage : storage}).single(‘myfile’);
  13. app.get(‘/’,function(req,res){
  14.       res.sendFile(__dirname + “/index.html”);
  15. });
  16. app.post(‘/uploadKreationnext’,function(req,res){
  17.     upload(req,res,function(err) {
  18.         if(err) {
  19.             return res.end(“Error uploading file.”);
  20.         }
  21.         res.end(“File is uploaded successfully!”);
  22.     });
  23. });
  24. app.listen(2000,function(){
  25.     console.log(“Server is running on port 2000”);
  26. });

To install the package.json, execute the following code:

  1. npm install

expressjs-fileupload2

It will create a new folder “node_modules” inside the “jtp file upload” folder.

expressjs-fileupload3

Dependencies are installed. Now, run the server:

  1. node server.js

expressjs-fileupload4.jpg

Open the local page http://127.0.0.1:2000/ to upload the images.

expressjs-fileupload5

Select an image to upload and click on “Upload Image” button.

expressjs-fileupload6.jpg

Here, you see that file is uploaded successfully. You can see the uploaded file in the “Uploads” folder.

expressjs-fileupload7.jpg

Download Node.js Express File Upload Example

Comments

comments