Renaming an uploaded file using Multer doesn't work (Express.js)

后端 未结 6 1711
孤独总比滥情好
孤独总比滥情好 2021-02-07 20:43

I\'m trying to upload a file from a HTML form using Express.js and Multer. I\'ve managed to save the file to the desired location (a folder named uploads).

Howe

6条回答
  •  眼角桃花
    2021-02-07 21:33

    we give a random name to file with the help of date and appends the original file extension with help of file.mimetype

    try console.log(file.mimetype) you will get the file name and extension separated by '/' then I split it to array and fetch the extension from it. Try the below code.

    let storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, './uploads')
      },
      filename: function (req, file, cb) {
        let extArray = file.mimetype.split("/");
        let extension = extArray[extArray.length - 1];
        cb(null, file.fieldname + '-' + Date.now()+ '.' +extension)
      }
    })
    const upload = multer({ storage: storage })
    

提交回复
热议问题