fasthtml
fasthtml copied to clipboard
[BUG] Uploading a single file on a multiple file field requires a try/except blog
Describe the bug
If a file input is set to multiple=True
and only a single file is selected on upload the form handler requires this try/except block or it throws a TypeError
:
@rt('/upload-multiple')
async def post(files: list[UploadFile]):
try: iter(files)
except TypeError: files = [files]
Minimal Reproducible Example
from fasthtml.common import *
from pathlib import Path
app, rt = fast_app()
upload_dir = Path("filez")
upload_dir.mkdir(exist_ok=True)
@rt('/')
def get():
return Titled("File Upload Demo",
P('Upload 1 to display failure but multiples work fine'),
Article(
Form(Input(type="file", name="files", multiple=True),
Button("Upload", type="submit", cls='contrast'),
hx_post="/upload-multiple", hx_target="#result-multiple"),
Div(id="result-multiple")
)
)
def FileMetaDataCard(file):
return Article(
Header(H3(file.filename)),
Ul(Li('Size: ',file.size),Li('Content Type: ',file.content_type))
)
@rt('/upload-multiple')
async def post(files: list[UploadFile]):
# Uncomment to show current method to resolve the problem described
# try: iter(files)
# except TypeError: files = [files]
cards = []
for file in files:
filebuffer = await file.read()
(upload_dir / file.filename).write_bytes(filebuffer)
cards.append(FileMetaDataCard(file))
return cards
serve()
Expected behavior
The list[UploadFile]
type on a handler's arguments should cast a single submitted UploadFile
to list[UploadFile]
. Something like:
try: iter(files)
except TypeError: files = [files]
Environment Information Please provide the following version information:
- fastlite version: 0.0.11
- fastcore version: 1.7.13
- fasthtml version: 0.6.10
Confirmation Please confirm the following:
- [x] I have read the FAQ (https://docs.fastht.ml/explains/faq.html)
- [x] I have provided a minimal reproducible example
- [x] I have included the versions of fastlite, fastcore, and fasthtml
- [x] I understand that this is a volunteer open source project with no commercial support.