简体   繁体   中英

FastAPI POST - Error 422 detail'': ( ( loc'':(body file msg'':field required'', type'': value_error missing)))

I want to read in backend this xlsx file. When I use the swagger I get it, but when I test in frontend I receive an Error 422 - devtools/Network detail'': ( ( loc'':(body file msg'':field required'', type'': value_error missing))).

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)

react ->

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>

I faced similar issue by trying to create python pop request for FastAPI demo file upload . Working from docs where it gave me ready code in form of curl line:

curl -X 'POST' \
  'http://127.0.0.1:8000/uploadfile/' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'file=@test_file'

(FastAPI auto generated docs page). Which i used as hint and from which I got that header for file name should be in the form of "type": "multipart/form-data", files = { "file": test_file_descriptor } And it worked

More exact: key for the file descriptor should be file . My case (Python): test_response = requests.post(test_url, data={'filename': test_file, "msg":"hello","type": "multipart/form-data"}, files = { "file": test_file } ) Where test_file is file descriptor. I know that my case might be different, but this is the only meaningful google link for this error, and someone with my case could also use it.

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