INTRODUCTION
Multer is a knot. js middleware for handling multipart/ form- data, which is primarily used for uploading lines. It's written on top of busboy for maximum effectiveness. NOTE Multer won't reuse any form which isn't multipart( multipart/ form- data).
Multer is aNode.js middleware for handling multipart/ form- data that makes the else meticulous process of uploading lines inNode.js much easier. In this composition, we ’ll learn the purpose of Multer in handling lines in submitted forms. We ’ll also explore Multer by erecting a mini app with a frontend and backend to test uploading a train.
PREREQUISITE
- NODE JS and NPM should have already installed in your computer.
- Basic knowledge of
- NODE, EXPRESS
- multer
- nodemon
and after creating project install express, multer package on your project by following commands:
npm install express
npm install multer
CREATING PROJECT
Create a NOJE.JS project by entering the command "npm init -y" , Here -y is optional
After hitting the command you get package.json and following response in terminal
CODE EXAMPLES
- Project Structure
- Add "type": "module" in package.json file and Add "start": "nodemon ." inside 'scripts' components in package.json file .
- Importing and creating server
import express from "express" import multer from "multer" const app=express() app.use(express.json()) app.use(express.urlencoded({extended:false})) app.listen(5000,(req,res)=>{ console.log("Server is running"); })
- Creating route for Uploading files
app.post('/upload',upload.array('image',10),async (req,res)=>{
res.json("file uploaded")
})
- Coding file uploading code with diskStorage and Filter and configuring Multer
const multarStorage=multer.diskStorage({
destination:(req,file,cb)=>{
cb(null,"public");
},
filename:(req,file,cb)=>{
const ext=file.mimetype.split("/")[1]
cb(null,`/admin-${file.fieldname}-${Date.now()}.${ext}`)
}
})
// Multer Filter
const multerFilter = (req, file, cb) => {
if (file.mimetype.split("/")[1] === "png" || file.mimetype.split("/")[1]==="jpeg") {
cb(null, true);
} else {
cb(new Error("Not a image File!!"), false);
}
};
//multer configuration
const upload=multer({
storage:multarStorage,
fileFilter: multerFilter,
})
RUNNING A PROJECT
OUTPUT/RESULT
For result use postman or thunder client for calling route
0 Comments