Trying to upload multiple files through a dynamic HTML form using FastAPI.
Server-side, the form comes through okay (as type starlette.datastructures.FormData
) but the files are not coming through. all i can see are the filenames as strings.
As per the docs, if i try:
@app.post("/modules/function")
async def function(request: Request):
form = await request.form()
filename = form["upload_file"].filename
contents = await form["upload_file"].read()
it fails with 'str' object has no attribute 'read'
on line 4.
From the docs, form["upload_file"]
is supposed to be type starlette.datastructures.UploadFile
but i am getting it as type str
.
Seemingly obvious solution is to declare files in path, but since form is dynamic, i can't tell how many files will be coming each time, so i need to be able to retrieve them from the FormData
.
Any pointers?
CodePudding user response:
Found it. Simple error. include enctype="multipart/form-data"
in html form tag. It doesn't automatically default to this when you include a file upload.