The multer npm package is a middleware used for handling multipart/form-data, which is primarily used for file uploads in Node.js applications. It allows you to upload files to your server with ease, making it one of the most popular file upload libraries in the Node.js ecosystem.
javascriptimport multer from 'multer';import { v4 as uuid } from 'uuid'; // for unique identification
javascriptconst storage = multer.diskStorage({// Define the destination folder for uploaded filesdestination(req, file, callback) {callback(null, 'uploads');},// Define the filename for the uploaded filefilename(req, file, callback) {const id = uuid(); // Generate a unique ID for each file using UUID v4const extName = file.originalname.split('.').pop(); // Extract the file extension from the original namecallback(null, `${id}.${extName}`); // Construct the new filename with the UUID and original file extension},});
javascriptexport const singleUpload = multer({ storage }).single('image');
This code sets up a file upload handler using multer in an Express application. It configures multer to:
typescriptimport express from "express";import { singleUpload } from "./middlewares/multer.js";const port = 3000;const app = express();app.use(express.json());app.use(express.urlencoded({ extended: true }));app.use("/uploads", express.static("uploads"));app.post("/register", singleUpload, (req, res) => {const { username } = req.body;const image = req.file ? req.file.filename : null;res.status(200).json({message: "User registered successfully",user: {username,image: image ? `/uploads/${image}` : null,},});});app.listen(port, () => {console.log(`Server running on http://localhost:${port}`);});
javascriptapp.use(express.json());app.use(express.urlencoded({ extended: true }));app.use("/uploads", express.static("uploads"));
javascriptapp.post("/register", singleUpload, (req, res) => {const { username } = req.body;const image = req.file ? req.file.filename : null;
javascriptres.status(200).json({message: "User registered successfully",user: {username,image: image ? /uploads/${image} : null,},});});
javascriptapp.listen(port, () => {console.log(`Server running on http://localhost:${port}`);});
The code sets up an Express server that handles JSON and URL-encoded form data, serves static files from an "uploads" directory, processes file uploads through middleware, and responds to registration requests with user information and uploaded file URLs
With Database setup
typescript//app.tsimport express from "express";import { singleUpload } from "./middlewares/multer.js";import { connectToDB } from "./models/userSchema.js";import User from "./models/userSchema.js";const port = 3000;const app = express();const URI = "mongodb://localhost:27017/multer"; // Ensure your DB name is correct// Connect to the databaseconnectToDB(URI);app.use(express.json());app.use(express.urlencoded({ extended: true }));app.use("/uploads", express.static("uploads"));app.post("/register", singleUpload, async (req, res) => {try {const { username } = req.body;const avatar = req.file ? req.file.filename : null;// Check for missing fieldsif (!username || !avatar) {return res.status(400).json({message: "Please enter all required fields (username and avatar).",});}// Check if the user already existsconst userExist = await User.findOne({ username });if (userExist) {return res.status(400).json({message: "User already exists.",});}// Create a new userawait User.create({username,avatar,});res.status(201).json({message: "User created successfully.",});} catch (error) {console.error("Error creating user:", error);res.status(500).json({message: "Internal server error.",});}});app.listen(port, () => {console.log(`Server running on http://localhost:${port}`);});
Delete Image from uploads folder and Db
typescriptimport express from "express";import { rm } from "fs";import path from "path";import { connectToDB } from "./models/userSchema.js";import User from "./models/userSchema.js";import mongoose from "mongoose";import { singleUpload } from "./middlewares/multer.js";const port = 3000;const app = express();const URI = "mongodb://localhost:27017/multer"; // Ensure your DB name is correct// Connect to the databaseconnectToDB(URI);app.use(express.json());app.use("/uploads", express.static("uploads"));app.post("/register", singleUpload, async (req, res) => {try {const { username } = req.body;const avatar = req.file ? req.file.filename : null;// Check for missing fieldsif (!username || !avatar) {return res.status(400).json({message: "Please enter all required fields (username and avatar).",});}// Check if the user already existsconst userExist = await User.findOne({ username });if (userExist) {return res.status(400).json({message: "User already exists.",});}// Create a new userawait User.create({username,avatar,});res.status(201).json({message: "User created successfully.",});} catch (error) {console.error("Error creating user:", error);res.status(500).json({message: "Internal server error.",});}});app.delete("/remove/:id", async (req, res) => {const { id } = req.params;// Validate the ObjectId formatif (!mongoose.Types.ObjectId.isValid(id)) {return res.status(400).json({message: "Invalid User ID format.",});}try {const user = await User.findById(id);if (!user) {return res.status(404).json({message: "User not found.",});}// Delete the avatar image if it existsif (user.avatar) {const avatarPath = path.join(process.cwd(), "uploads", user.avatar);rm(avatarPath, (err) => {if (err) {console.error("Error deleting file:", err);return res.status(500).json({message: "Error deleting user avatar.",});}console.log("User avatar deleted.");});}// Delete the user from the databaseawait User.findByIdAndDelete(id);res.json({message: "User deleted successfully.",});} catch (error) {console.error("Error deleting user:", error);res.status(500).json({message: "Internal server error.",});}});app.listen(port, () => {console.log(`Server running on http://localhost:${port}`);});
Update Avatar
typescriptapp.put("/profile/:id", singleUpload, async (req, res) => {const id = req.params.id;const { username } = req.body;const avatar = req.file ? req.file.filename : null; //get imageconst user = await User.findById(id); //find userif (!user)return res.status(404).json({message: "user not found",});if (username) user.username = username; //Updates the username if a new value is provided.if (avatar) {//remove oldSaved Avatarconst removeOldAvatar = path.join(process.cwd(),"uploads",user.avatar as string);//if nott remove then show errorrm(removeOldAvatar, (err) => {if (err)return res.status(500).json({message: "Image not delete for update",});console.log("image delete");});user.avatar = avatar; //update the avatr if a new avatar value provide}await user.save(); //user save after updateres.status(200).json({message: "user updated",});});
The PUT /profile/:id endpoint allows you to update a user’s profile, including their username and avatar. It checks for the existence of the user, updates the necessary fields, handles the deletion of the old avatar file if a new one is provided, and finally saves the updated user details to the database. If any errors occur during this process, appropriate status codes and messages are sent back to the client.
⭐ Give a star and follow :
ayanhasnain03 (Ayan Hasnain) (github.com)
🔗 Check out my LinkedIn for updates and learn new things with my easy-peasy notes: