How to handle Images ?


Multer is a Node package that handles file uploads. Whenever you build a website using Node.js and Express, Multer is often used for uploading files.
Multer is a Node.js middleware for handling multipart/form-data
, which is primarily used for uploading files.
Note: Multer will not process any form that is not of type multipart/form-data
.
Installation
$ npm install --save multer
HHere, we’ll cover Disk Storage.
First, we must define two things: the destination
and filename
for the uploaded image. It’s essential to generate a unique name for each image file. That's why we use randomly generated bytes with each file name. In the example below, we generate 12 random bytes, but you can choose any size.
const multer = require("multer");
const crypto = require("crypto");
const path = require("path")
// diskstorage
const storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'./public/images/uploads');
},
filename:function(req,file,cb){
crypto.randomBytes(12,function(err,bytes){
const np = bytes.toString("hex") + path.extname(file.originalname)
cb(null,np)
})
}
})
// expload upload variable
const upload = multer({storage:storage})
module.exports = upload
Folder structure
Create an Upload Page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Form</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div class="min-h-screen w-screen bg-zinc-950 py-4 px-2">
<h3 class="text-white font-bold text-4xl">Update profile File</h3>
<form action="/upload" enctype="multipart/form-data" method="post" class="px-2 py-5 flex flex-row gap-5 items-center">
<input type="file" name="image">
<button type="submit" class="px-8 py-2 bg-blue-500 font-bold text-xl rounded-md outline-none text-zinc-200">Upload File</button>
</form>
</div>
</body>
</html>
Render the Upload Page
app.get('/profile/upload',(req,res)=>{
res.render("profileupload")
})
Serve Static Files
app.use(express.static(path.join(__dirname,"public")));
Handle the Upload and Save Filename to DB
const upload = require('./config/multerconfig');
app.post("/upload",isLoggedIn, upload.single("image"), async (req, res) => {
let user = await userModel.findOne({email:req.user.email});
user.profilepic = req.file.filename;
await user.save()
res.redirect("/profile");
});
Display the Profile Picture
app.get('/profile',isLoggedIn,async (req,res) =>{
let user = await userModel.findOne({email:req.user.email}).populate('post')
res.render('profile',{user})
})
User Model
const mongoose = require('mongoose');
mongoose.connect("mongodb://127.0.0.1:27017/User");
const userSchema = mongoose.Schema({
username: String,
name:String,
age:Number,
email: String,
password: String,
profilepic:{
type:String,
default:"default.png"
},
post:[{
type:mongoose.Schema.Types.ObjectId,ref:'post'
}]
})
module.exports = mongoose.model('user',userSchema);
This completes your basic setup for handling file uploads in a Node.js/Express app using Multer.
Subscribe to my newsletter
Read articles from Harsh Patel directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
