How to store a file with file extension with multer?

后端 未结 11 1645
情话喂你
情话喂你 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:34

    There may be some issues in the already answered codes.

    • There may be some cases of files with no extension.
    • There should not be an upload.any() usage. Its vulnerable to the attackers
    • The upload function should not be global .

    I have written the below codes for better security.

    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
    
            cb(null, 'temp/')
        },
        filename: function (req, file, cb) {
            let ext = ''; // set default extension (if any)
            if (file.originalname.split(".").length>1) // checking if there is an extension or not.
                ext = file.originalname.substring(file.originalname.lastIndexOf('.'), file.originalname.length);
            cb(null, Date.now() + ext)
        }
    })
    var upload = multer({ storage: storage });
    

    Using it for upload

    // using only single file object name (HTML name attribute)
    // May use upload.array(["file1","file2"]) for more than one
    app.post('/file_upload', upload.single("file"), function (req,res) {
        //console.log(req.body, 'Body');
        console.log(req.file, 'file');
        res.send("cool");
    })
    

提交回复
热议问题