首页 > 解决方案 > 使用 multer 上传图像文件时出现问题(React 和 Node.js)

问题描述

我花了几个小时试图找到应该非常简单的解决方案:从客户端上传文件到服务器。我在前端使用 React.js,在后端使用 Express,并multer用于图像上传。

当我尝试上传文件时,没有任何反应。创建了一个uploads/目录,但没有文件到那里。req.file并且req.filesundefinedreq.body.file是空的。表单数据在发送之前就存在。

如果我将Content-Type标题设置为,"multipart/form-data"我会从multer.

输入

<input 
    onChange={this.sendFile}
    name="avatar"
    placeholder="Choose avatar"
    type="file"
/> 

发送文件

sendFile = e => {
    const data = new FormData();
    const file = e.target.files[0];
    data.append("file", file);
    this.props.sendFile(data);
};

还原动作

export default file => async dispatch => {
    const res = await axios.post("/api/upload/", { file });
};

表达

const multer = require("multer");
const upload = multer({ dest: "uploads/" });

router.post("/upload/", upload.single("avatar"), (req, res) => {
    return res.sendStatus(200);
});

标签: node.jsreactjsexpressmulter

解决方案


我试图重现它并使它与这种方法一起工作:

sendFile = e => {
  const data = new FormData();
  const file = e.target.files[0];
  data.append("avatar", file); // <-- use "avatar" instead of "file" here
  axios({
    method: 'post',
    url: 'http://localhost:9000/api/upload',
    data: data,
    config: { headers: { 'Content-Type': 'multipart/form-data' } }
  });
};

推荐阅读