Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading an excel file to FastAPI from a React app

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?

like image 645
jon-perrett Avatar asked Nov 22 '25 22:11

jon-perrett


1 Answers

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).

like image 188
lsabi Avatar answered Nov 25 '25 11:11

lsabi