当我使用 multer 和 html 输入表单上传图像时,req.file 未定义

req.file is undefined when I upload image using multer and html input form

我想使用 nodeJS 和 multer 上传图片,所以我做了以下操作:

下面是我的multer配置:

var multer = require('multer');

var storage = multer.diskStorage({

    //Setting up destination and filename for uploads
    destination: function (req, file, cb) {  
        cb(null, 'uploads/');
    },
    filename: function (req, file, cb) {  
        cb(null, Date.now() + file.originalname);
    }

});

var upload = multer({
    storage: storage,
    limits:{
        fieldSize: 1024*1024*6,
    }
});

下面是我上传图片的路径:

router.post('/designer', upload.single('designerImage'), async (req, res) => {
    console.log(req.file);

    //rest of the code which is not needed for my query
})

当我 POST 使用 form-data 类型 file 键的文件 [=27] 时,它工作得很好=]POST男人。但是当我尝试使用 HTML 表单输入发送它时,req.file 结果是 undefined 并且没有文件上传到 uploads 文件夹.下面是我的 HTML 表单代码:

<form action="/designer" method="POST">
    <input type="file" name="designerImage">
<form>

这个问题的解决方案是什么?我已经花了几个小时但无法找到解决方案。

multer only parses multipart/form-data 请求,因此您需要在表单中添加 enctype="multipart/form-data"

<form action="/designer" method="POST" enctype="multipart/form-data">
    <input type="file" name="designerImage">
<form>