node.js - 使用 multer 上传图像文件时出现问题(React 和 Node.js)
问题描述
我花了几个小时试图找到应该非常简单的解决方案:从客户端上传文件到服务器。我在前端使用 React.js,在后端使用 Express,并multer
用于图像上传。
当我尝试上传文件时,没有任何反应。创建了一个uploads/
目录,但没有文件到那里。req.file
并且req.files
是undefined
。req.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);
});
解决方案
我试图重现它并使它与这种方法一起工作:
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' } }
});
};
推荐阅读
- amazon-web-services - 配置 AWS API 网关时是否需要 NAT 网关?
- postgresql - 为什么我的 luminus 应用不能在 Heroku 上运行?
- reactjs - React 路由器在 URL 栏中不起作用,但它仍然适用于标签
- unicode - Ocaml:Unicode 字符串长度
- javascript - 循环遍历两个对象数组以循环匹配 id。然后根据自定义值返回一个新的自定义对象数组
- pytorch - PyTorch 训练的模型可以在 GPU 和 TPU 之间转移吗?
- sql-server - 创建一个 Powershell 脚本以禁用大多数 SQL Server 登录
- c - 每次进入循环时,如何从文本文件中读取下一行?
- python - 不确定为什么我在使用搁置时遇到回溯问题
- sql-server - 更改 EF Core DB 中列错误的 IDENTITY 属性