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>
UploadFile
requires that you send a form withenctype="multipart/form-data
and aninput type="file"
field. Since you haven't included whatcreate
does, I'm guessing that it submits the content as JSON and not as a multipart form post. If you want to submit a JSON body (as is common from a Javascript application such as react), you can instead use a pydantic model that matches your JSON strucuture and encode the file data as base64 data, which you deserialize on the server side. – LodgingsFormData
, using the key defined in your endpoint, i.e.,file
, and the file object obtained from an<input type="file">
element. For instance,var formData = new FormData(); formData.append("file", fileInput.files[0]);
. Please have a look at the answers here, as well as here and here, for more details. – Jarrell