从React应用程序将Excel文件上传到FastAPI

从React应用程序将Excel文件上传到FastAPI

问题描述:

好吧,我真的希望有关该主题的其他各种问题之一对我有帮助,但我根本无法完成这项工作!我对React和使用API​​请求相对较新.我想从我的React应用程序上传一个excel文件,然后使用FastAPI作为界面在python中对其进行处理.

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.

我已经遵循了各种教程/文档方法,但是我刚遇到422无法处理的实体错误!

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

在React中,我的事件处理程序如下所示:

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
        });
    };

当上传"按下按钮,附加到FormData对象并通过axios请求发送(数据库是axios对象):

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);
    };

我的FastAPI处理程序如下所示:

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?

您的问题与以下原因相同

Your problem is due to the same reason as

如何将文件发送到fastapi端点使用邮递员

fastapi终结点中的文件变量名称必须与表单数据文件的键名称相匹配.也就是说,您的javascript应该像

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

,以便您的端点能够访问 file 参数.否则,请更改参数的名称(在您的情况下为 UploadFile ).

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