hiteshchoudhary / chai-backend

A video series on chai aur code youtube channel
5.06k stars 760 forks source link

Error When The Avatar File and CoverImage File Have Same Name #125

Closed anmol420 closed 1 week ago

anmol420 commented 4 months ago

Getting an error when i upload same files in avatarfile and coverimage ! I guess this edge case wasn't checked !

Probable Solution -

if (avatarLocalPath === coverImageLocalPath) {
        throw new ApiError(400, "Both Images Have Same Name.");
}
Devendra616 commented 4 months ago

My solution would be to keep the avatar name and cover image different by adding suffix like avatarFilename = "avatar-"+ avatarLocalPath coverimageFilename = "cover-"+ coverimageFilename

anmol420 commented 4 months ago

The full code for the middleware of multer will be :

import multer from "multer";
import path from "path";

// direct from multer's github repo

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./public/temp");
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
        const extension = path.extname(file.originalname);
        cb(null, file.fieldname + "-" + uniqueSuffix + extension);
    },
});

export const upload = multer({ storage: storage });

Added Path for getting the extension of the file entered by the user.