Not able to save image with original name and extension through multer in node.js

Viewed 54

Hi I am trying to save an image in my image folder through multer but the issue is that the file is being saved with a randomly generated filename without extension.I have tried to resolve this issue by referring to various articles but still facing the same issue.

referred the following : Multer is not saving the file as the same name and without extension?

The file gets saved in the image folder like below : a9bfcba8e950ccfbdaf7f0d2f8d58374

Hence if someone could please help me resolve this issue.

profile.js

const upload = multer({
    dest:'images',
    filename: function (req, file, cb) { 
      cb(null, file.originalname) 
    },
    limits: {
        fileSize: 10000000,
    },
    fileFilter(req, file, cb) {
       if(!file.originalname.match(/\.(jpg|jpeg|png|JPG|HEIC)$/)) {
           return cb(new Error('Please attach an image'))
       }
       cb(undefined, true);
    }
})

router.post('/user/upload', upload.single('profile_pic') , async (req,res) => {
    console.log(req.body)

    const url = req.protocol + '://' + req.get('host')
   
    //when inserting the file in the database we are able to send the exact location with original file name and extension.

    var filepath = url + '/Users/images/';
    var reqFiles = (filepath + req.file.filename + path.extname(req.file.originalname) 
    console.log(req.file);
   

    const notify = new user({
        userId: req.body.userId,
        profile_pic: reqFiles  

    })
1 Answers

you need to do step wise process for storing a file.

//storage for image upload
const storage = multer.diskStorage({
    destination: './upload',
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

//file filter for extention
let fileFilter = function (req, file, cb) {
    console.log(file.mimetype)
    const allowedMimes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];

    if (allowedMimes.includes(file.mimetype)) {
        cb(null, true);
    } else {
        cb(null, false);
    }
};

//upload for to pass storage, file size limit and filter
//maximum file size is 10Mb
const upload = multer({
    storage: storage,
    limits: { fileSize: 10 ** 7 },
    fileFilter: fileFilter
}).single('userImage');

then call your route.

router.post('/upload', (req,res)=>{

    upload(req, res, (err)=>{
        if(err){
            console.log(err)
        }
        else{
            console.log(req.file)
            console.log(req.file.path)
        }
    })
})

By following this approach then definitely your error will solved.

Related