Search code examples
node.jsmulter

Multer is returning a empty response


I am uploading an image but when I am trying to implement a function so that I can change the file name to include the date once it has been stored.

With the code below how it is I will get an empty object back but still a successful message. But if I uncomment the in the code it will work but it will not include the date.

const express = require("express");
const multer = require("multer");
const app = express();

const fileFilter = function(req, file, cb){
    const allowedTypes = ["image/jpeg","image/png", "image/gif"];

    if(!allowedTypes.includes(file.mimetype)) {
        const error = new Error("wrong file type");
        error.code = "LIMIT_FILE_TYPES";
        return cb(error, false);
    }
    cb(null, true);
}
const storage = multer.diskStorage({
    destination:function(req, file, cb){
        cb(null, './uploads/')
    },
    filename:function(req, file, cb){
        cb(null, file + '-' + Date.now())
    }
});

const MAX_SIZE = 200000
const upload = multer({
    // dest: './uploads/', If I un-comment this line it will upload the image but will not change file name will still be random hash numbers
    fileFilter,
    storage:storage,
    limits:{
        fileSize: MAX_SIZE
    }
});

app.post('/upload', upload.single('file'), (req, res) => {
    res.json({file:req.file});
});

app.use(function(err, req, res, next) {
    if(err.code === "LIMIT_FILE_TYPES") {
        res.status(422).json({error:"Only Images are Allowed"});
        return;
    }
    if (err.code ==="LIMIT_FILE_SIZE"){
        res.status(422).json({error:`Size is to Large, Max size is ${MAX_SIZE/ 
  1000}KB`});
        return;
    }
});

app.listen(3344, () => console.log("running local on 3344"));

Solution

  • It returns undefined since you are making a string combining the file object + '-' + Date.now() so change this line:

    cb(null, file + '-' + Date.now())
    

    to this one:

    cb(null, file.fieldname + '-' + Date.now())
    

    It should do the job.