首页 > 解决方案 > 如何将 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>
    );
  }
}

标签: reactjsflask

解决方案


您可以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);
    });
  });
}

推荐阅读