File Upload Input
Demonstrates how to preserve file inputs after form errors
from fasthtml.common import Button, Div, Form, Input, Label, fast_app
from starlette.datastructures import UploadFile
app, rt = fast_app()
form_name = "binaryForm"
def my_form(*children):
return Form(enctype="multipart/form-data", hx_swap="outerHTML", hx_post=submit, hx_target="this", id=form_name)(
Button("Submit"),
*children,
)
@app.get
def page():
return Div(
# Move file input out of the form
Label("An error should happen when you click on submit button. But the uploaded file should NOT be cleared"),
Input(form=form_name, type="file", name="binaryFile"),
my_form(),
)
@app.post
async def submit(binaryFile: UploadFile):
return my_form(Div("Error: Try again", style="color:red"))
@rt
def bad_form():
# This bad implementation
# Users are required to re-upload the file in case of error on other fields
return Form(hx_swap="outerHTML", hx_post=bad_form, hx_target="this")(
Input(type="file", name="binaryFile"),
Button("Submit"),
)