FastAPI StreamingResponse:异步文件生成时触发浏览器立即下载问题
解决方案:让浏览器立即触发异步生成文件的下载
要解决Chrome/Firefox需等待首字节才启动下载的问题,同时避免文件开头出现多余字符,可以通过自定义StreamingResponse并发送零字节块的方式实现,具体步骤如下:
核心思路
- 自定义StreamingResponse:重写响应的流处理逻辑,确保空字节块也会被发送(默认FastAPI会跳过空块)。
- 提前发送零字节块:在文件生成等待阶段,先发送一个
b''(零字节),触发浏览器立即显示下载状态,且不会污染文件内容。
修改后的完整代码
import asyncio from fastapi import FastAPI from fastapi.responses import StreamingResponse from urllib.parse import quote app = FastAPI() class CustomStreamingResponse(StreamingResponse): async def stream_response(self, send): await send({"type": "http.response.start", "status": self.status_code, "headers": self.raw_headers}) async for chunk in self.body_iterator: # 不跳过空字节块,确保浏览器能收到首响应触发下载 await send({"type": "http.response.body", "body": chunk, "more_body": True}) await send({"type": "http.response.body", "body": b"", "more_body": False}) async def async_read_file(): # 发送零字节块触发浏览器立即启动下载 yield b'' # 模拟文件生成的等待过程(最长30秒) count = 0 while count < 5: await asyncio.sleep(2) count += 1 # 安全读取生成好的文件 with open('file.zip', 'rb') as file: while True: data = file.read(64 * 1024) if not data: break yield data @app.get('/download') async def download(): async def iterate_file_(): async for chunk in async_read_file(): yield chunk response = CustomStreamingResponse( iterate_file_(), headers={ "Content-Disposition": f"attachment; filename*=utf-8''{quote('file.zip')}" } ) return response
关键说明
- 自定义Response的作用:默认的
StreamingResponse会忽略空字节块,导致浏览器无法收到首响应而延迟触发下载;自定义后即使是空块也会发送,让浏览器感知到数据传输已开始。 - 零字节块的安全性:
b''是零长度字节,不会向下载的文件中写入任何内容,因此不会破坏文件结构或导致加载问题。 - 资源安全:使用
with语句打开文件,确保文件在读取完成后自动关闭,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Valerio De Blasio
相关产品推荐
相关产品推荐

