File uploading in Node.js - GeeksforGeeks

14 Jan, 2020
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:
It’s easy to get started and easy to use.It is widely used and popular module for file uploading.Users can upload either single or multiple files at a time.
It’s easy to get started and easy to use.
It is widely used and popular module for file uploading.
Users can upload either single or multiple files at a time.
Installation of Multer module:
You can visit the link Install multer module. You can install this package by using this command.npm install multerAfter installing multer you can check your multer version in command prompt using the command.npm version multerAfter 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.jsRequiring module: You need to include multer module in your file by using these lines.var multer = require('multer');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.jsconst express = require("express")const path = require("path")const multer = require("multer")const app = express()    // View Engine Setupapp.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 optionalconst 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 processapp.listen(8080,function(error) {    if(error) throw error        console.log("Server created Successfully on PORT 8080")})Steps to run the program:The project structure will look like this:Here “uploads” is the folder where our files will be uploaded, currently it is empty. The “Singup.ejs” is kept in the views folder.Make sure you have ‘view engine’ like I have used “ejs” and also install express and multer using following commands:npm install ejsnpm install expressnpm install multerRun index.js file using below command:node index.jsOpen browser and type this URL:http://localhost:8080/Then you will see the Singup form as shown below:Then choose a file to be uploaded and click on submit button.If error occurs, then following message will be displayed:And if no errors occurs, then following message will be displayed:If file uploading process successful, then you can go to the uploads folder and see your uploaded image as shown below: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_upSave
You can visit the link Install multer module. You can install this package by using this command.npm install multer
npm install multer
After installing multer you can check your multer version in command prompt using the command.npm version multer
npm version multer
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
node index.js
Requiring module: You need to include multer module in your file by using these lines.var multer = require('multer');
var multer = require('multer');
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.jsconst express = require("express")const path = require("path")const multer = require("multer")const app = express()    // View Engine Setupapp.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 optionalconst 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 processapp.listen(8080,function(error) {    if(error) throw error        console.log("Server created Successfully on PORT 8080")})Steps to run the program:The project structure will look like this:Here “uploads” is the folder where our files will be uploaded, currently it is empty. The “Singup.ejs” is kept in the views folder.Make sure you have ‘view engine’ like I have used “ejs” and also install express and multer using following commands:npm install ejsnpm install expressnpm install multerRun index.js file using below command:node index.jsOpen browser and type this URL:http://localhost:8080/Then you will see the Singup form as shown below:Then choose a file to be uploaded and click on submit button.If error occurs, then following message will be displayed:And if no errors occurs, then following message will be displayed:If file uploading process successful, then you can go to the uploads folder and see your uploaded image as shown below: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_upSave
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()    // View Engine Setupapp.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 optionalconst 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 processapp.listen(8080,function(error) {    if(error) throw error        console.log("Server created Successfully on PORT 8080")})
Steps to run the program:
The project structure will look like this:Here “uploads” is the folder where our files will be uploaded, currently it is empty. The “Singup.ejs” is kept in the views folder.Make sure you have ‘view engine’ like I have used “ejs” and also install express and multer using following commands:npm install ejsnpm install expressnpm install multerRun index.js file using below command:node index.jsOpen browser and type this URL:http://localhost:8080/Then you will see the Singup form as shown below:Then choose a file to be uploaded and click on submit button.If error occurs, then following message will be displayed:And if no errors occurs, then following message will be displayed:If file uploading process successful, then you can go to the uploads folder and see your uploaded image as shown below:
The project structure will look like this:Here “uploads” is the folder where our files will be uploaded, currently it is empty. The “Singup.ejs” is kept in the views folder.
Make sure you have ‘view engine’ like I have used “ejs” and also install express and multer using following commands:npm install ejsnpm install expressnpm install multer
npm install ejs
npm install express
npm install multer
Run index.js file using below command:node index.js
node index.js
Open browser and type this URL:http://localhost:8080/
http://localhost:8080/
Then you will see the Singup form as shown below:
Then choose a file to be uploaded and click on submit button.If error occurs, then following message will be displayed:And if no errors occurs, then following message will be displayed:
If file uploading process successful, then you can go to the uploads folder and see your uploaded image as shown below:
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.
Node.js-Misc
Node.js
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.sendFile() Function
Mongoose | findByIdAndUpdate() Function
Express.js res.redirect() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript