3

Ok, I was really hoping that one of the various other questions on this topic would help me but I simply can't make this work! I'm relatively new to React and using API requests. I'm looking to upload an excel file from my React app and then process it in python using FastAPI as the interface.

I've followed the various tutorials / documentation approaches and I just get a 422 Unprocessable Entity Error!

In React, my event handlers look like this:

When file is selected, set the file in state:

    onFileChange = (event) => {
        this.setState({
            uploadFile: event.target.files[0],
            isFileSelected: true
        });
    };

When the "Upload" button is pressed, append to a FormData object and send via an axios request (Database is the axios object):

   onUploadClick = async (event) => {
        event.preventDefault()
        var formData = new FormData();

        formData.append(
            "UploadFile",
            this.state.uploadFile,
            this.state.uploadFile.name
        );

        this.setState({isFileUploaded: true})
        console.log(this.state.uploadFile)

        const headers={'Content-Type': this.state.uploadFile.type}
        
        await Database.post("/FileUpload",formData,headers);
    };

And my FastAPI handler looks like this:

@app.post("/FileUpload")
async def FileUpload(file: UploadFile = File(...)):
    # do some things...

Can someone please put me out my misery?

jon-perrett
  • 94
  • 1
  • 6
  • Does this answer your question? [How to send a base64 encoded image to a FastAPI backend?](https://stackoverflow.com/questions/64788970/how-to-send-a-base64-encoded-image-to-a-fastapi-backend) – Chris Apr 25 '23 at 05:35
  • Related answers can also be found [here](https://stackoverflow.com/a/74588435/17865804), as well as [here](https://stackoverflow.com/a/70655118/17865804) and [here](https://stackoverflow.com/a/71478057/17865804) – Chris Apr 25 '23 at 05:37

1 Answers1

2

Your problem is due to the same reason as

How to send file to fastapi endpoint using postman

The name of the file variable in your fastapi endpoint has to match the name of the key to the file of your formdata. That is, your javascript should be like

formData.append(
    "file",
    this.state.uploadFile,
    this.state.uploadFile.name
);

in order for your endpoint to be able to access the file parameter. Otherwise change the parameter's name (UploadFile in your case).

lsabi
  • 3,641
  • 1
  • 14
  • 26