反应图像上传到 FastAPI 不可处理的实体

React image upload to FastAPI Unprocessable Entity

我使用 FastApi 创建了一个 API 来处理上传的图像和 return 处理过的图像。

这里是图片上传端点

@app.post("/predict")
async def root(file: UploadFile = File(...)):
..............................
res,im_png = cv2.imencode(".png", bg_img)
    return StreamingResponse(io.BytesIO(im_png.tobytes()), media_type="image/png")

我在前端做了什么:

class Detect extends Component {

  state = {
    title: '',
    content: '',
    image: null
  };

  handleChange = (e) => {
    this.setState({
      [e.target.id]: e.target.value
    })
  };

  handleImageChange = (e) => {
    this.setState({
      image: e.target.files[0]
    })
  };

  handleSubmit = (e) => {
    e.preventDefault();
    console.log(this.state);
    let form_data = new FormData();
    form_data.append('image', this.state.image, this.state.image.name);
    let url = 'http://127.0.0.1:8000/predict';
    axios.post(url, form_data, {
      headers: {
        'content-type': 'multipart/form-data'
      }
    })
        .then(res => {
          console.log(res.data);
        })
        .catch(err => console.log(err))
  };

  render() {
    return (
      <div className="App">
        <form onSubmit={this.handleSubmit}>

          <p>
            <input type="file"
                   id="image"
                   accept="image/png, image/jpeg"  onChange={this.handleImageChange} required/>
          </p>
          <input type="submit"/>
        </form>
      </div>
    );
  }
}

export default Detect;

当我通过前端上传图片并提交时,API 显示 “无法处理的实体”,而当我使用 Swagger 时它工作正常 UI.

我认为图像没有被 FastApi 接收为它可以处理的类型 我该如何解决这个问题??

您应该将图像添加到 FormData 对象,使用在文件上传端点中定义的相同 key(在您的情况下,即 file)。因此,你应该这样做:

form_data.append('file', this.state.image, this.state.image.name);