Nodejs express image file upload usingh multer example; In this tutorial, i am going to show you how to upload image file in node js express using multer library.
Multer is a middleware for handling multipart/form-data, extremely useful for managing file uploads. You can use Express. js middleware framework to build the single or multiple file upload system along with Multer and Node. js.
Node js express file upload example; i will create html file upload form and install node modules for file storing into directory. Then create a routes; which is used to show file upload form and store file into node js express app directory.
How to Upload File in Node js Expres using Multer Example
- Step 1 – Create Node JS App
- Step 2 – Install Express and Multer Modules
- Step 3 – Create Server.js File and Import Modules into it
- Step 4 – Create Routes
- Step 5 – Create File Upload Form
- Step 6 – Start App Server
Step 1 – Create Node JS App
Execute the following command on terminal to create node js app:
mkdir my-app cd my-app npm init
Step 2 – Install Express and Multer Modules
Install required node js modules; So 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 and Import Modules into it
Create server.js file; so visit your app root directory and create it. The import above installed node js modules into it; as shown below:
const express = require('express'); const multer = require('multer'); const path = require('path'); const sharp = require('sharp');
Step 4 – Create Routes
Create routes for file upload; so open your server.js file and add the following routes into it:
// Include the express module into the poject for creating the server const express = require("express") // Include the multer module into the project for accepting files const multer = require("multer") // Include the path module to extract file extension from every file entering the server. const path = require("path") // We will set the object received from the express() function to a variable "app" const app = express() // Set a port on which the server will run on const port = 3000 const upload = multer({ storage: multer.diskStorage({ destination: "/upload/images", // Storage location filename: (req, res, (cb) => { cb(null, Date.now() + path.extname(file.originalname)) // return a unique file name for every file }) }), limits: {fileSize: 20000000}, // This limits file size to 2 million bytes(2mb) fileFilter: fileFilter: (req, file, cb) => { // Create regex to match jpg and png const validFileTypes = /jpg|jpeg|png/ // Do the regex match to check if file extenxion match const extname = fileTypes.test(path.extname(file.originalname).toLowerCase()) if(mimetype && extname){ // Return true and file is saved return cb(null, true) }else{ // Return error message if file extension does not match return cb("Error: Images Only!") } } }).single("myImage") app.post("/upload", (req, res) => { // This is the response sent to the user in the browser once the file recieved upload(req, res, (err) => { if(err){ res.send(err) // This will display the error message to the user } else{ res.send("File Uploaded Successfully") // This shows the file has beem successfully uploaded // The image will be found in the public folder } }) }) // Create the server and let it run on the port 3001 app.listen(port, () => { console.log(`Server is running on port ${port}`) })
Step 5 – Create File Upload Form
Create index.html file; add the following html markup code for file upload form:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>File Upload</title> </head> <body> <div class="container"> <h1>File Upload</h1> <!--Create a form to send the file to a route "upload"--> <!--Set the request method to POST--> <!--Set the encytype to "multipart/form-data" in order to send files and not just text--> <form action="/upload" method="POST" enctype="multipart/form-data"> <div class="file-field input-field"> <div class="btn grey"> <input type="file" name="myImage"> </div> </div> <button class="btn" type="submit">Submit</button> </form> </div> </body> </html>
Step 6 – Start App Server
Execute the following on terminal to start app server:
//run the below command npm start after run this command open your browser and hit http://127.0.0.1:3000/
Conclusion
Node js express file image upload using multer, sharp and express js. In this tutorial, you have learned how to upload file image using multer, sharp and express js.