【问题标题】:req.file is undefined when I upload image using multer and html input form当我使用 multer 和 html 输入表单上传图像时,req.file 未定义
【发布时间】:2020-07-19 10:39:55
【问题描述】:

我想使用 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
})

当我使用 POSTMAN 使用 file 类型的 form-data 键发布文件时,它工作得非常好。但是当我尝试使用 HTML 表单输入发送它时,req.file 变成了undefined,并且没有文件被上传到 uploads 文件夹。下面是我的 HTML 表单代码:

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

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

【问题讨论】:

    标签: node.js forms file-upload postman multer


    【解决方案1】:

    multeronly parsesmultipart/form-data 请求,所以您需要在表单中添加enctype="multipart/form-data"

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-14
      • 2021-05-02
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多