How To File Upload Using Node.js

Websolutionstuff | Jul-26-2021 | Categories : Node.js

In this example, we will delve into the process of performing file uploads using Node.js. This tutorial will provide you with a straightforward demonstration of file uploads in Node.js, specifically with Express.js and the Multer module.

We'll use the Multer module, a widely-used Node.js middleware, to handle multipart/form-data, making it the go-to choice for file uploads in web applications. By the end of this tutorial, you'll have a clear understanding of how to implement file uploads, enhancing the functionality of your Node.js applications

Visit Multer Package : Install Multer Module

So, an example of file upload in node js and express js using multer. let's start.

Step 1: Create Node App

In this step create node application using below command

mkdir express_js_file_upload

cd express_js_file_upload

npm init

 

 

Step 2: Install Embedded JavaScript templates (ejs)

 In this step, we install ejs using below command

npm install ejs

 

Step 3: Install express.js in App

Now install Express in the express_js_file_upload directory and save it in the dependencies list. For example:

$ npm install express --save

 

Step 4: Install multer in App

 In this step install multer using the below command. Also, you can visit the link Install multer module.

npm install multer

 

 

Step 5: Create File_upload_form.ejs

 in this step create File_upload_form.ejs in the views folder. and copy the below code in the file.

<!DOCTYPE html>
<html>
<head>
	<title>How To File Upload Using Node.js - Websolutionstuff</title>
</head>
<body>
    <h1>How To File Upload Using Node.js - Websolutionstuff</h1>   
    <form action="/uploadFile" enctype="multipart/form-data" method="POST">      
        <span>Upload File: </span>  
        <input type="file" name="pic" required/> <br>
        <input type="submit" value="submit"> 
    </form>
</body>
</html>

 

Step 6: Create index.js file

now create an index.js file in your app directory. and copy the below code in the index.js file

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("pic");       
  
app.get("/",function(req,res){
    res.render("File_upload_form");
})
    
app.post("/uploadFile",function (req, res, next) {
         
    upload(req,res,function(err) {
  
        if(err) {            
            res.send(err)
        }
        else {            
            res.send("Successfully Image uploaded..!")
        }
    })
})    
app.listen(3000);

and your file structure like the below image.

File Structure

Note: create an uploads folder in the app to store files.

 

Step 7: Run index.js file

run index.js using the below code

node index.js

 and after running this command you will get output like the below screenshot.

How To File Upload Using Node.js

 

You May Also Like:

Recommended Post
Featured Post
How To Disable Weekends In jQuery Datepicker
How To Disable Weekends In jQu...

In this tutorial, we will see how to disable weekend dates in jquery datepicker. In the date picker, the weeke...

Read More

Jun-27-2022

How To Send Email With Attachment In Laravel 8
How To Send Email With Attachm...

In this tutorial i will show you how to send email with attachment in laravel 8. As we all know mail functionalities are...

Read More

May-05-2021

How to Install PHP Soap Extension in Ubuntu 23.04
How to Install PHP Soap Extens...

Hey fellow developers! Today, let's tackle the installation of the PHP SOAP extension on our Ubuntu 23.04 systems. I...

Read More

Jan-31-2024

500 Internal Server Error In Laravel 9 AJAX
500 Internal Server Error In L...

In this article, we will see 500 internal server errors in laravel 9 ajax. Also, we can see how to solve or fixed l...

Read More

Apr-17-2022