node.js - 从 React 上传图像请求
问题描述
我想要实现的是从客户端(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 中得到了什么:链接
如果您想查看,我在代码沙箱中创建了一个片段:https ://codesandbox.io/s/heuristic-snyder-d67sn?file=/src/App.js
解决方案
添加此方法以捕获 onChange 事件:
为您的状态添加 2 个属性:picturePreview 和 pictureAsFile
uploadPicture = (e) => {
this.setState({
/* 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]
})
};
现在,在您的 onSubmit 事件中:
setImageAction = () => {
const formData = new FormData();
formData.append(
"file",
this.state.pictureAsFile
);
// do your post request
};
当然不要将 uploadPicture 方法添加到您的输入中:
<input type="file" name="image" onChange={this.uploadPicture}/>
编辑
显示您的 formData :
for (var key of formData.entries())
{
console.log(key[0] + ', ' + key[1])
}