Search code examples
javascriptpythonreactjsaxiosfastapi

Uploading Image from React to FastAPI raises 422 Unprocessable Entity error


I have created an API using FastAPI that processes the image uploaded and return the processed image.

Here is the image upload endpoint:

@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")

What I have done in the frontend:

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;

When I upload the image through the frontend and submit it, the API returns a 422 (Unprocessable Entity) error, while it was working fine when I was using Swagger UI.

What I believe is the image is not being received by FastAPI as a type that it can processed. How can I resolve this issue??


Solution

  • You should add your image to the FormData object, using the same key/parameter name used when the UplaodFile field was defined in the endpoint. In your case, that is, file, as shown in your example:

    @app.post("/predict")
    async def root(file: UploadFile = File(...)):
        pass       ^^^^
    

    Hence, in your frontend, you should use that name when adding the image to the FormData object:

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

    For more details, please have a look at this answer and this answer.