Home > database >  Can't upload image from a Reactjs front-end to FastApi
Can't upload image from a Reactjs front-end to FastApi

Time:11-15

I have an API endpoint that can processes image. And the API endpoint works fine I checked it properly. But when I try to upload a image file with my Reactjs front-end it doesn't works and gives me a HTTP 422 error code.

I am using axios to post the image. This is my Reactjs upload method. (I am quite to ReactJs.)

    onClickHandler = () => {
        const data = new FormData()

        var host = window.location.protocol   "//"   window.location.host   "/api/image" 

        data.append('file', this.state.selectedFile)

        axios.post(host, data, {
            //headers: {
            //    'Content-Type': 'multipart/form-data'
            //},
            
            // This just for the progress bar
            onUploadProgress: ProgressEvent => {
                this.setState({
                    loaded: (ProgressEvent.loaded / ProgressEvent.total*100),
                    })
                },
            })
          .then(res => { // then print response status
            toast.success('upload success')
          })
          .catch(err => { // then print response status
            toast.error('upload fail')
          })
    }

This the request header from the Swagger UI. enter image description here enter image description here

This the request header from my Reactjs App. enter image description here enter image description here

FastApi's response. enter image description here

CodePudding user response:

According to the body of the 422 error message FastAPI is expecting a field named image to be submitted. In your frontend code you're using the field name file. These two need to match, so either change your frontend code to use the name image or your backend to expect the name file instead.

  • Related