reactjs - 如何将 React 表单中的多个文件上传到 Flask API?
问题描述
我正在尝试使用 React,我正在尝试将多个图像上传到烧瓶中的 API 以进行保存。我能够弄清楚如何上传单个文件,但正在努力转换为多个文件。这是单次上传的代码。
烧瓶
@app.route('/upload', methods={"POST"})
def upload_file():
file = request.files.getlist("file")
print(file)
response="Whatever you wish to return"
return response
反应
export default class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
};
this.handleUploadImage = this.handleUploadImage.bind(this);
}
handleUploadImage(ev) {
ev.preventDefault();
const data = new FormData();
data.append('file', this.uploadInput.files[0]);
fetch('http://localhost:5000/upload', {
method: 'POST',
body: data,
}).then((response) => {
response.json().then((body) => {
});
});
}
render() {
return (
<form onSubmit={this.handleUploadImage}>
<div>
<input ref={(ref) => { this.uploadInput = ref; }} type="file" />
</div>
<br />
<div>
<button>Upload</button>
</div>
</form>
);
}
}
解决方案
您可以multiple
在文件上设置属性,input
以便选择多个文件:
<input
ref={(ref) => {
this.uploadInput = ref;
}}
type="file"
multiple
/>
然后你可以改变你的handleUploadImage
功能,让它发送所有选择的文件:
handleUploadImage(ev) {
ev.preventDefault();
const data = new FormData();
for (let i = 0; i < this.uploadInput.files.length; i++) {
data.append("file", this.uploadInput.files[i]);
}
fetch("http://localhost:5000/upload", {
method: "POST",
body: data,
}).then((response) => {
response.json().then((res) => {
console.log(res);
});
});
}
推荐阅读
- php - 为什么我的应用程序处理来自后端字符串的数组?
- flutter - 删除 Firestore 表中的地图
- python - Flask,将数据帧作为 JSON 传递给客户端以显示它
- amazon-web-services - 将预先存在的静态(弹性)IP 分配给 EC2 实例
- android - 带有字符串Android的可绘制资源文件
- cypress - Cypress - 无法在 chrome/Firefox 上运行 cypress runner,但能够在我的工作笔记本电脑上运行
- php - 如何只为 100 个 laravel Web 服务器 php-fpm 进程创建一个 websocket 客户端连接?
- jquery - Shopify 价格变化方程
- node.js - 如何使用变量来实现updateOne的$set操作路径?
- linux - linux(ubuntu)或git中的文件路径中的...是什么意思