简体   繁体   中英

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

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. 在此处输入图片说明 在此处输入图片说明

This the request header from my Reactjs App. 在此处输入图片说明 在此处输入图片说明

FastApi's 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM