[Fixed] multer saves image in a weird format

Issue

I am trying to serve an image from my Express server to my client but multer is saving the file in a weird format which leads to issues when my react app tries to render the image

multer server side code:

const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
        // accept a file
        cb(null, true);
    } else {
        // reject a file
        cb(new Error('Incorrect file'), false);
    }
}
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/');
    },
    filename: (req, file, cb) => {
        cb(null, Date.now() + path.extname(file.originalname))
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 5 // max 5mb for image size
    },
    fileFilter: fileFilter
});

router.post('/', upload.single('productImage'), ProductsController.products_create_product);

This code successfully creates the file in the /uploads folder but when I save the path to the database I get this response:

Postman

{
    "size": 5,
    "quantityInStock": 11,
    "productImage": "uploads\\2021-03-11T19-18-05.442Zvans-2.jpg",
}

How can I change it so it saves the image in this format: /uploads/2021-03-11T19-18-05.442Zvans-2.jpg

Solution

You just need to fix your destination path like this:

cb(null, path.join(__dirname, './uploads/'));

For me this was the full code-block. Just grab the actual part you want:

const multer = require('multer');
const path = require('path');

const appConfigs =  require('./../config/app');

module.exports = function (folderName) {
    // TODO: console log here and optimize multiple initialization of multer if need
    return multer({
        storage: multer.diskStorage({
            destination: function (req, file, cb) {
                const filePath = path.join(__dirname, './../uploads/' + folderName);
                cb(null, filePath);
            },
            filename: function (req, file, cb) {
                const extension = file.mimetype.split('/')[1];
                const fileName = (new Date().getTime() / 1000 | 0) + '.' + extension;
                cb(null, fileName);
            }
        }),
        limits: {
            fileSize: 1024 * 1024 * appConfigs.image_max_size // MB
        },
        fileFilter: (req, file, cb) => {
            let valid = (file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png');
            cb(null, valid);
        },
    });
};

Leave a Reply

(*) Required, Your email will not be published