FastAPI/Starlette, Web UI: Save File Dialog, Open File Dialog

  fastapi, python, starlette

I’ve been studying this example project. Very concise and to the point, and a pleasant surprise, too: a Save File Dialog (a standard desktop File Dialog, opened from Chrome).

The responsible code:

def form_post(request: Request, num: int = Form(...), multiply_by_2: bool = Form(False), action: str = Form(...)):
    if action == 'convert':
        result = spell_number(num, multiply_by_2)
        return templates.TemplateResponse('download.html', context={'request': request, 'result': result, 'num': num})
    elif action == 'download':
        # Requires aiofiles
        result = spell_number(num, multiply_by_2)
        filepath = save_to_text(result, num)
        return FileResponse(filepath, media_type='application/octet-stream', filename='{}.txt'.format(num))


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Sample Form</title>
<form method="post">
    <input type="number" name="num" value="{{ num }}"/>
    <input type="checkbox" id="multiply_by_2" name="multiply_by_2" value="True">
    <label for="multiply_by_2">Multiply by 2&nbsp;</label>
    <input type="submit" name="action" value="convert">
    <input type="submit" name="action" value="download">
<p>Result: {{ result }}</p>

I can’t see any hint on a File Dialog in FileResponse, much less on the Save File Dialog, which pops up. I want the Open File Dialog too, by the way. I tried to research it, without success.

How does it work?

Source: Python Questions