File uploading in Node.js

Introduction: File uploading means a user from client machine requests to upload file to the server. For example, users can upload images, videos, etc on Facebook, Instagram, etc.

Features of Multer module: File can be uploaded to the server using Multer module. There are other modules in market but multer is very popular when it comes to file uploading. Multer is a node.js middleware which is used for handling multipart/form-data, which is mostly used library for uploading files.

Note: Multer will process only those form which are multipart (multipart/form-data). So whenever you use multer, make sure you put multipart in form.



Introduction:

  1. It’s easy to get started and easy to use.
  2. It is widely used and popular module for file uploading.
  3. Users can upload either single or multiple files at a time.

Installation of Multer module:

  1. You can visit the link Install multer module. You can install this package by using this command.
    npm install multer
  2. After installing multer you can check your multer version in command prompt using the command.
    npm version multer
  3. After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.
    node index.js
  4. Requiring module: You need to include multer module in your file by using these lines.
    var multer = require('multer');
  5. So Multer basically adds a file object or files object and a body object to the request object. The file/files object contains all the files which are uploaded through the form and all the values of the text fields of the form are contained in the body object. This is how multer binds the data whenever a form is submitted.

    Filename: Signup.ejs

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!DOCTYPE html>
    <html>
      
    <head>
        <title>FILE UPLOAD DEMO</title>
    </head>
      
    <body>
        <h1>Single File Upload Demo</h1>
       
        <form action="/uploadProfilePicture" 
          enctype="multipart/form-data" method="POST">
          
            <span>Upload Profile Picture:</span>  
            <input type="file" name="mypic" required/> <br>
            <input type="submit" value="submit"
        </form>
    </body>
      
    </html>

    chevron_right

    
    

    Filename: index.js

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    const express = require("express")
    const path = require("path")
    const multer = require("multer")
    const app = express()
        
    // View Engine Setup
    app.set("views",path.join(__dirname,"views"))
    app.set("view engine","ejs")
        
    // var upload = multer({ dest: "Upload_folder_name" })
    // If you do not want to use diskStorage then uncomment it
        
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
      
            // Uploads is the Upload_folder_name
            cb(null, "uploads")
        },
        filename: function (req, file, cb) {
          cb(null, file.fieldname + "-" + Date.now()+".jpg")
        }
      })
           
    // Define the maximum size for uploading
    // picture i.e. 1 MB. it is optional
    const maxSize = 1 * 1000 * 1000;
        
    var upload = multer({ 
        storage: storage,
        limits: { fileSize: maxSize },
        fileFilter: function (req, file, cb){
        
            // Set the filetypes, it is optional
            var filetypes = /jpeg|jpg|png/;
            var mimetype = filetypes.test(file.mimetype);
      
            var extname = filetypes.test(path.extname(
                        file.originalname).toLowerCase());
            
            if (mimetype && extname) {
                return cb(null, true);
            }
          
            cb("Error: File upload only supports the "
                    + "following filetypes - " + filetypes);
          
      
    // mypic is the name of file attribute
    }).single("mypic");       
      
    app.get("/",function(req,res){
        res.render("Signup");
    })
        
    app.post("/uploadProfilePicture",function (req, res, next) {
            
        // Error MiddleWare for multer file upload, so if any
        // error occurs, the image would not be uploaded!
        upload(req,res,function(err) {
      
            if(err) {
      
                // ERROR occured (here it can be occured due
                // to uploading image of size greater than
                // 1MB or uploading different file type)
                res.send(err)
            }
            else {
      
                // SUCCESS, image successfully uploaded
                res.send("Success, Image uploaded!")
            }
        })
    })
        
    // Take any port number of your choice which
    // is not taken by any other process
    app.listen(8080,function(error) {
        if(error) throw error
            console.log("Server created Successfully on PORT 8080")
    })

    chevron_right

    
    

    Steps to run the program:

    1. The project structure will look like this:
      project structure
      Here “uploads” is the folder where our files will be uploaded, currently it is empty. The “Singup.ejs” is kept in the views folder.
    2. Make sure you have ‘view engine’ like I have used “ejs” and also install express and multer using following commands:
      npm install ejs
      npm install express
      npm install multer
    3. Run index.js file using below command:
      node index.js

      Output of above command

    4. Open browser and type this URL:
      http://localhost:8080/
    5. Then you will see the Singup form as shown below:
      This is the sample form for uploading single image
    6. Then choose a file to be uploaded and click on submit button.
      If error occurs, then following message will be displayed:
      Error Message
      And if no errors occurs, then following message will be displayed:
      Success Message
    7. If file uploading process successful, then you can go to the uploads folder and see your uploaded image as shown below:
      Uploaded Image

    So this is how you can upload file in Node.js using multer module. There are other modules in the market for file uploading like fileupload, express-fileupload etc.




    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.