使用 multer 上传图像文件时出现问题(React 和 Node.js)
Problems uploading image file with multer (React and Node.js)
我花了几个小时试图找到解决方案,但应该非常简单:从客户端将文件上传到服务器。我在前端使用 React.js,在后端使用 Express,在上传图片时使用 multer
。
当我尝试上传文件时,没有任何反应。创建了一个 uploads/
目录,但没有文件进入该目录。 req.file
和 req.files
是 undefined
。 req.body.file
为空。表单数据在发送前已经存在
如果我将 Content-Type
header 设置为 "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);
};
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);
});
尝试在axios请求中将content-type header设置为multipart/form-data
并发送完整的FormData object作为第二个参数。
像这样:
const config = {
headers: {
'content-type': 'multipart/form-data'
}
};
axios.post('/api/upload/', file, headers);`
我尝试重现它并使用此方法使其工作:
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' } }
});
};
我花了几个小时试图找到解决方案,但应该非常简单:从客户端将文件上传到服务器。我在前端使用 React.js,在后端使用 Express,在上传图片时使用 multer
。
当我尝试上传文件时,没有任何反应。创建了一个 uploads/
目录,但没有文件进入该目录。 req.file
和 req.files
是 undefined
。 req.body.file
为空。表单数据在发送前已经存在
如果我将 Content-Type
header 设置为 "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);
};
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);
});
尝试在axios请求中将content-type header设置为multipart/form-data
并发送完整的FormData object作为第二个参数。
像这样:
const config = {
headers: {
'content-type': 'multipart/form-data'
}
};
axios.post('/api/upload/', file, headers);`
我尝试重现它并使用此方法使其工作:
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' } }
});
};