FastAPI StreamingResponse start download while waiting for data #11526
Unanswered
valeriodeblasio-1
asked this question in
Questions
Replies: 1 comment 1 reply
-
@valeriodeblasio-1 you can do this with the @app.get("/download")
async def download():
async def iterate_file_():
async for chunk in async_read_file():
yield chunk
response = StreamingResponse(
iterate_file_(),
headers={
"Content-Type": "application/force-download", # 👈
"Content-Disposition": "attachment; filename*=utf-8''{}".format("file.zip"),
},
)
return response |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
First Check
Commit to Help
Example Code
Description
I want to send a file to a user, however the file is generated asynchronously via a thread which can take a long time (even 30 seconds).
I would like the browser to show the file being downloaded right away (with 0 bytes and unknown size), tried via cUrl and it works but with a browser (Chrome or Firefox) this doesn't happen, the download only starts after the first bytes have been sent.
The only way I've been able to find is to send empty characters (\u200B) while waiting for the file to be generated (as suggested in this similar problem Chrome doesn't show file as being downloaded until 8 bytes are sent (Firefox does)), but this way the resulting file contains these characters at the beginning, which then gives problems when loading on other systems.
Operating System
Linux, macOS
Operating System Details
No response
FastAPI Version
0.109.2
Pydantic Version
2.1.1
Python Version
3.11.2
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions