Node js multiple image upload using multer, sharp and express js. In this tutorial guide, you will learn how to upload multiple image file using multer, sharp and express js.
Image upload is the basic requirement of any application. So this example will guide you step by step on how to upload multiple images using multer. And you can understand a concept of multiple image upload.
How to Upload Multiple Image File Using Multer in Node.js and Express
Let’s follow the following steps to upload multiple image files using multer in node js express:
- Step 1 – Create Node JS App
- Step 2 – Install Express and Multer Dependencies
- Step 3 – Create Server.js File
- Step 4 – Create Multiple File Image Upload Form
- Step 5 – Start Node Express Js App Server
Step 1 – Create Node JS App
In this step, open your terminal and execute the following command to create node js app:
mkdir my-app cd my-app npm init -y
Step 2 – Install Express and Multer Dependencies
In this step, open again your terminal and execute the following command to install express and multer dependencies in your node js app:
npm install express multer --save npm install sharp --save
Step 3 – Create Server.js File
In this step, you need to create server.js file and add the following code into it:
const express = require('express'); const multer = require('multer'); const path = require('path'); const app = express(); const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, 'uploads/'); }, filename: function(req, file, cb) { cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); } }); var upload = multer({ storage: storage }) app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); app.post('/', upload.array('multi-files'), (req, res) => { res.redirect('/'); }); app.listen(3000);
Step 4 – Create Multiple File/Image Upload Form
In this step, create index.html file to resize image before upload in node js app. So, add the following html code into it:
<!DOCTYPE html> <html lang="en"> <head> <title>Node js Express Multiple Image Upload using Multer Example - Tutsmake.com</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h1>Node js Express Multiple Image Upload using Multer Example - Tutsmake.com</h1> <form action="/" enctype="multipart/form-data" method="post"> <input type="file" name="multi-files" accept='image/*' multiple> <input type="submit" value="Upload"> </form> </body> </html>
Click to know more about the express.
Step 5 – Start Node Express Js App Server
You can use the following command to run development server:
//run the below command npm start after run this command open your browser and hit http://127.0.0.1:3000/
Conclusion
In this tutorial, you have learned how to upload multiple images in node js using multer.
this is awesome blog for understanding in shortly