admin管理员组

文章数量:1287584

const diskStorage = multer.diskStorage({
    destination: 'uploads/',
    filename: (req, file, cb) => {
        cb(null, Date.now() + file.originalname);
    }
});

why we cant assign file name directly ?

const diskStorage = multer.diskStorage({
    destination: 'uploads/',
    filename: "myfile.png" // ❌ This gives an error
});
const diskStorage = multer.diskStorage({
    destination: 'uploads/',
    filename: (req, file, cb) => {
        cb(null, Date.now() + file.originalname);
    }
});

why we cant assign file name directly ?

const diskStorage = multer.diskStorage({
    destination: 'uploads/',
    filename: "myfile.png" // ❌ This gives an error
});
Share Improve this question edited Feb 23 at 14:46 Karl-Johan Sjögren 17.6k7 gold badges63 silver badges72 bronze badges asked Feb 23 at 14:42 Naga mani kanta manamNaga mani kanta manam 394 bronze badges 1
  • 1 This configures the engine — it’s unlikely you’d want the engine to overwrite the file on each request (you could, of course, with a one-liner that returns a string, barely longer than the string itself). – Dave Newton Commented Feb 23 at 14:58
Add a comment  | 

2 Answers 2

Reset to default 2

Multer needs filename as a function cuz filenames should be dynamic, not fixed. If you set it as "myfile.png", every upload will overwrite the last one. The function lets you use file.originalname, timestamps, etc., and ensures async handling with cb().

So yeah, it's just how Multer works to avoid conflicts and allow flexibility!

本文标签: