【问题标题】:req.file is undefined while using multer for image upload使用 multer 进行图像上传时 req.file 未定义
【发布时间】:2021-05-02 06:34:54
【问题描述】:

我在使用 multer 上传图像时遇到 req.file 未定义错误。我正在使用 FormData 将我的图像从 react 发送到 nodejs。我已经查看了 Stack Overflow 的几乎所有解决方案,但我无法解决问题。

我用于发送文件的 React 代码:

const data = new FormData();
    data.append('profile',e.target.files[0]);
    axios.post('/imagefilter', data).then(res=>console.log(res)).catch(err=>console.log(err))

我接收文件的输入标签:

<input type="file" onChange={(e) => { onChange(e) }} />

nodejs服务器代码:

 const storage = multer.diskStorage({
destination: (req,file,cb) => {
    console.log(req.files);
    cb(null,path.join(__dirname, './uploads'))
},
filename: (req,file,cb) => {
    cb(null,file.originalname);
}

})

发布路线:

router.post(`/imagefilter`,upload.single('profile'),(req, res) => { console.log(req.file)})

我无法找出错误,我已经浪费了将近 24 小时来修复此错误。

【问题讨论】:

    标签: node.js reactjs multer


    【解决方案1】:

    我认为当你调用 api 时,你需要在 header 中添加 Content-Type": "multipart/form-data。

    【讨论】:

    • 我尝试在 axios 中使用标头,但 req.file 仍然未定义。而且,当我使用邮递员获取请求时,我收到了这个错误。
    【解决方案2】:

    其实我是用的

    app.use(fileUpload())
    

    在我创建 imagefilter 路由之前,当我删除 fileUpload() 时问题解决了

    【讨论】:

      猜你喜欢
      • 2016-04-14
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 2018-08-06
      • 1970-01-01
      • 2021-10-02
      相关资源
      最近更新 更多