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

后端 未结 6 1705
孤独总比滥情好
孤独总比滥情好 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:41

    File has structure like this:

    {
    "fieldname": "avatar",
    "originalname": "somefile.pdf",
    "encoding": "7bit",
    "mimetype": "application/pdf",
    "destination": "./uploads",
    "filename": "36db44e11b83f4513188f649ff445a2f",
    "path": "uploads\\36db44e11b83f4513188f649ff445a2f",
    "size": 1277191
    

    }

    The next example saves file with it's original name an extension and not with the strange name like it is by default. (Instead of "file.originalname" you can save it as you want)

    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, './uploads') //Destination folder
      },
      filename: function (req, file, cb) {
        cb(null, file.originalname) //File name after saving
      }
    })
    
    var upload = multer({ storage: storage })
    

提交回复
热议问题