【问题标题】:Why does request.files not have the files that were sent?为什么 request.files 没有发送的文件?
【发布时间】:2021-02-24 01:15:26
【问题描述】:

我正在尝试使用 fetch 将文件上传到烧瓶。我所做的是 onChange 将文件放在 useState 挂钩中,然后 onSubmit 将其附加到 FormData。在我使用 fetch 将文件发送到我的烧瓶 api 之后。我做出了回应,告诉我文件是否存在,并且它一直以空白字典的形式返回。

这是反应代码。

import React, {useState} from 'react'

function App() {
  const [file, setFile] = useState(null);
  const fileInserted = (event) => setFile(event.target.value);
  const handleSubmit = async (event) => {
    event.preventDefault();
    if (file) {
      const data = new FormData();
      data.append("file", file);
      const resp = await fetch("/run", {
        method: "POST",
        body: data,
      }).then(res => res.json())
      .then(data => console.log(data.file))
      .catch(error => console.error(error))
    }
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="file"
          onChange={fileInserted}
        />
        <button type="submit" disabled={!file}>Submit</button>
      </form>
    </div>
  );
}

export default App;

这是烧瓶代码。

    @app.route("/run", methods=['GET', 'POST'])
    def index():
        if request.method == "POST":
            if 'file' not in request.files:
                return {"file": request.files}
            file = request.files['file']
            return {"file": file}
        else:
            return {"file": "this a get"}

【问题讨论】:

  • 因为您的 FormData 在每次渲染组件时都会重新创建。

标签: reactjs flask post fetch


【解决方案1】:

您填充的 ​​FormData 在每次渲染时都会重新创建为空对象。

您也不需要使用效果挂钩来运行 fetch...

function App() {
  const [file, setFile] = useState(null);
  const fileInserted = (event) => setFile(event.target.value);
  const handleSubmit = async (event) => {
    if (file) {
      const data = new FormData();
      data.append("file", file);
      const resp = await fetch("/run", {
        method: "POST",
        body: data,
      });
      // TODO: handle error/success
    }
    event.preventDefault();
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="file"
          value={file}
          onChange={fileInserted}
        />
        <button type="submit" disabled={!file}>Submit</button>
      </form>
    </div>
  );
}

export default App;

【讨论】:

  • 我已经更新了我的代码以匹配你的代码,但是烧瓶响应仍然告诉我没有找到文件。我将更新问题以显示新代码。
猜你喜欢
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 2011-06-23
  • 1970-01-01
  • 2021-11-16
  • 2014-04-12
  • 2019-07-03
  • 2023-04-06
相关资源
最近更新 更多