File uploading in Node.js – GeeksforGeeks

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




    <!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>

    
    

    
    

    Filename: index.js




    const express = require("express")

    const path = require("path")

    const multer = require("multer")

    const app = express()

        

    app.set("views",path.join(__dirname,"views"))

    app.set("view engine","ejs")

        

        

    var storage = multer.diskStorage({

        destination: function (req, file, cb) {

      

            

            cb(null, "uploads")

        },

        filename: function (req, file, cb) {

          cb(null, file.fieldname + "-" + Date.now()+".jpg")

        }

      })

           

    const maxSize = 1 * 1000 * 1000;

        

    var upload = multer({ 

        storage: storage,

        limits: { fileSize: maxSize },

        fileFilter: function (req, file, cb){

        

            

            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);

          

      

    }).single("mypic");       

      

    app.get("/",function(req,res){

        res.render("Signup");

    })

        

    app.post("/uploadProfilePicture",function (req, res, next) {

            

        

        

        upload(req,res,function(err) {

      

            if(err) {

      

                

                

                

                res.send(err)

            }

            else {

      

                

                res.send("Success, Image uploaded!")

            }

        })

    })

        

    app.listen(8080,function(error) {

        if(error) throw error

            console.log("Server created Successfully on PORT 8080")

    })

    
    

    
    

    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 “Signup.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 Signup 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