FastAPI POST - 错误 422 详细信息'': ( ( loc'':(body file msg'':field required'', type'': value_error Missing)))

mvi*_*rra 6 python forms post typescript fastapi

我想在后端读取这个 xlsx 文件。当我使用 swagger 时,我得到了它,但是当我在前端测试时,我收到错误 422 - devtools/网络详细信息'': ( ( loc'':(body file msg'':field required'', type'': value_error 丢失)))。

router = APIRouter()

@router.post('/')
async def upload_file(file: Uploadfile = File(...)):

  try:
    arquivo = await file.read()
    df_cambio = pd.read_excel(arquivo)
    cambio_dict = df_cambio.to_dict('index')
    
    print(cambio_dict)
    return{"file_name": file.filename}
  
  except Exception as e:
    exception_handler(e)
Run Code Online (Sandbox Code Playgroud)

反应->

export defaut function Dropzone() {
const [create, {isLoading}] = usePost();

const handleSubmit = (res) => {
    create('cambios', { data:res.file }})
};
if (isLoading) { return <LoadingPageSkeleton />;}

return (

<BasicForm
  initialValues={{}}
  onSubmit={handleSubmit}
>
    <FormInput id="file />
    <FormSubmitButton/>
</Basicform>
Run Code Online (Sandbox Code Playgroud)

mik*_*olo 2

我尝试为 FastAPI 演示文件上传创建 python pop 请求时遇到了类似的问题。从docs它为我提供了卷曲行形式的准备代码的地方开始工作:

curl -X 'POST' \
  'http://127.0.0.1:8000/uploadfile/' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'file=@test_file'
Run Code Online (Sandbox Code Playgroud)

(FastAPI 自动生成的文档页面)。我用它作为提示,从中我得到文件名的标头应该采用以下形式"type" : "multipart/form-data" , files = { "file" : test_file_descriptor }并且它有效

更准确地说:文件描述符的键应该是file. 我的情况(Python): 文件描述符在test_response = requests.post(test_url, data={'filename': test_file , "msg":"hello" ,"type" : "multipart/form-data"}, files = { "file" : test_file } )哪里。test_file我知道我的情况可能有所不同,但这是此错误唯一有意义的谷歌链接,有我情况的人也可以使用它。