How to store a file with file extension with multer?

后端 未结 11 1607
情话喂你
情话喂你 2020-12-13 17:56

Managed to store my files in a folder but they store without the file extension.

Does any one know how would I store the file with file extension?

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 18:33

    I used this little trick to get file extension, and as a workaround to circumvent issues that might occur when someone uploads a file with similar file name twice, or that exists in the server.

    const path = require('path');
    const crypto = require('crypto');
    
    let upload = multer({
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, path.join(__dirname, '../uploads'))
        },
        filename: (req, file, cb) => {
            // randomBytes function will generate a random name
            let customFileName = crypto.randomBytes(18).toString('hex')
            // get file extension from original file name
            let fileExtension = path.extname(file.originalname).split('.')[1];
            cb(null, customFileName + '.' + fileExtension)
        }
      })
    })
    

提交回复
热议问题