使用multer(React和Node.js)上传图像文件时出现问题

时间:2018-10-12 08:54:21

标签: node.js reactjs express multer

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

当我尝试上传文件时,没有任何反应。已创建uploads/目录,但没有文件进入该目录。 req.filereq.filesundefinedreq.body.file为空。表单数据在发送之前就已经存在。

如果将Content-Type标头设置为"multipart/form-data",则会从multer收到边界错误。

输入

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

sendFile

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

Redux操作

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);
});

2 个答案:

答案 0 :(得分:1)

尝试在axios请求中将内容类型标头设置为multipart/form-data,然后将完整的FormData对象作为第二个参数发送。

赞:

const config = {
    headers: {
        'content-type': 'multipart/form-data'
    }
};
axios.post('/api/upload/', file, headers);`

答案 1 :(得分:1)

我试图重现它并使其通过以下方法起作用:

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' } }
  });
};
相关问题