从 React 上传图像请求
Posted
技术标签:
【中文标题】从 React 上传图像请求【英文标题】:Upload Image Request from React 【发布时间】: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
【问题讨论】:
【参考方案1】:添加此方法以捕获 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])
【讨论】:
我按照你的例子,现在可以显示上传的文件访问pictureAsFile;唯一的问题是 formData.append 不起作用。如果我试图显示它,我会得到一个空对象;知道为什么吗? 好吧FormData是一个特殊的对象,不能用console.log显示 另外,它不可字符串化,因此正文必须直接包含您的 FormData 我添加了一种方法来记录您的 dataForm 内容 抱歉没有回复,完全忘记了。无论如何我发现问题一直在网上寻找,发现是上传文件时不必设置的标题:“Content-Type”:“multipart/form-data”。通过删除那行代码,我解决了这个问题。不过,您的评论对我帮助很大。以上是关于从 React 上传图像请求的主要内容,如果未能解决你的问题,请参考以下文章