File/Image Upload With Multer in Node js and Express
Today, in this article, we will explain to you how to file/image upload with multer in node js and Express. so in this example, we are using the multer npm package for image upload in node js. we can easily image or file upload using multer in node js.
What is multer in node JS?
A multer is one type of npm package and it is a Node.js middleware for handling files. it is used to file uploading in node js.
So you can follow the below step for node js multer file upload example.
Step 1: Create the Application Directory.
First, we will open the command prompt and create the application directory in our directory. for this, you can follow the below command.
1 2 | mkdir nodejs_upload_image cd nodejs_upload_image |
Step 2: Install node js packages
In this step, we will create a package.json file in your application directory and paste the below code in this file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | { "name": "nodejs_upload_image", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1", "body-parser": "^1.19.0", "multer":"^1.4.2" } } |
now, you can run below command for install packages.
1 | npm install |
Or, You can also install using the following command
1 | npm install express multer body-parser --save |
Step 3: Create Server file
we will create a server.js file in your application directory and paste the below code in this file. here we will load the npm package.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | const express = require('express') const bodyParser= require('body-parser') const multer = require('multer'); const app = express(); const upload = multer({ dest: 'uploads/' }); app.use(bodyParser.urlencoded({extended: true})) app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); app.post('/uploadImage', upload.single('fileImage'), (req, res) => { res.redirect('/'); }); app.listen(3000,function(){ console.log("Express Started on Port 3000"); }); |
Step 4: Create the view file and upload directory
In this step, we will create the index.html file for the upload of the image and create the uploads directory.
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE html> <html lang="en"> <head> <title>File/Image Upload With Multer in Node js and Express - XpertPhp</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <form action="/uploadImage" enctype="multipart/form-data" method="post"> <input type="file" name="fileImage"> <input type="submit" value="Upload"> </form> </body> </html> |
Step 5: Run Application
Now, you can run your application following Url.
1 | https://localhost:3000/ |