【发布时间】:2020-08-25 06:08:59
【问题描述】:
我想要实现的是从客户端(React)向包含上传图像文件的服务器端(Express)发送请求
这是我在服务器上创建的表单示例,它发送我应该使用 React 发送的数据:
<form method="post" action="post" enctype="multipart/form-data">
<input type="file" name="image" /><br /><br />
<button type="submit" name="upload">Upload</button>
</form>
这是上传图片时提交的表单发送的对象:link
这里是 React 组件:
const Component = () => {
const setImageAction = async (event) => {
event.preventDefault();
const data = await fetch("http://localhost:3000/upload/post", {
method: "post",
headers: { "Content-Type": "multipart/form-data" },
body: JSON.stringify({
}),
});
const uploadedImage = await data.json();
if (uploadedImage) {
console.log('Successfully uploaded image');
} else {
console.log('Error Found');
}
};
return (
<div className="content">
<form onSubmit={setImageAction}>
<input type="file" name="image" />
<br />
<br />
<button type="submit" name="upload">
Upload
</button>
</form>
</div>
);
};
如您所见,在 React 组件中,正文请求为空,因为我还没有弄清楚如何检索该文件对象..
提前感谢您的帮助!
编辑
如图所示更新,唯一的区别是保持State为Hook
这里是新的 React 组件代码:
const LandingPage = () => {
const [picture, setPicture] = useState({});
const uploadPicture = (e) => {
setPicture({
/* contains the preview, if you want to show the picture to the user
you can access it with this.state.currentPicture
*/
picturePreview: URL.createObjectURL(e.target.files[0]),
/* this contains the file we want to send */
pictureAsFile: e.target.files[0],
});
};
const setImageAction = async (event) => {
event.preventDefault();
const formData = new FormData();
formData.append("file", picture.pictureAsFile);
console.log(picture.pictureAsFile);
for (var key of formData.entries()) {
console.log(key[0] + ", " + key[1]);
}
const data = await fetch("http://localhost:3000/upload/post", {
method: "post",
headers: { "Content-Type": "multipart/form-data" },
body: formData,
});
const uploadedImage = await data.json();
if (uploadedImage) {
console.log("Successfully uploaded image");
} else {
console.log("Error Found");
}
};
return (
<div className="content landing">
<form onSubmit={setImageAction}>
<input type="file" name="image" onChange={uploadPicture} />
<br />
<br />
<button type="submit" name="upload">
Upload
</button>
</form>
</div>
);
};
我从这些 console.logs 中得到什么:link
如果你想看看,我在代码沙箱中创建了一个 sn-p:https://codesandbox.io/s/heuristic-snyder-d67sn?file=/src/App.js
【问题讨论】:
标签: node.js reactjs api express