我有一个 GET 端点,它应该返回一个巨大的文件(500Mb)。 我正在使用
FileResponse
来做到这一点(为了清晰起见,简化了代码):
async def get_file()
headers = {"Content-Disposition": f"attachment; filename={filename}"}
return FileResponse(file_path, headers=headers)
然后该文件立即保存。
例如,我有一个大小为 500 MB 的文件,当我在 UI 上单击“下载”时,我必须等待一分钟或其他时间,直到显示“保存对话框”。然后,当我单击“保存”时,文件会立即保存。显然前端正在等待文件下载,我需要的是前端立即显示“保存对话框”,然后在后台开始下载。
我需要的是这样的:立即显示对话框,然后用户单击“保存”后等待下载完成。
那么我怎样才能实现这一目标呢?
如果您正在寻找一种方法来立即在前端启动下载提示,而无需等待整个文件被获取。实现此目的的一种方法是在服务器上使用异步文件生成并流式传输响应。这是在 Django 中使用
StreamingHttpResponse
的示例:
import mimetypes
from django.http import StreamingHttpResponse
from wsgiref.util import FileWrapper
async def generate_file_content(file_path):
with open(file_path, 'rb') as file:
for chunk in iter(lambda: file.read(8192), b''):
yield chunk
async def get_file(request):
file_path = "/path/to/your/file.txt" # Replace with your actual file path
filename = "your_file.txt" # Replace with your actual file name
response = StreamingHttpResponse(
streaming_content=generate_file_content(file_path),
content_type=mimetypes.guess_type(file_path)[0],
)
response['Content-Disposition'] = f'attachment; filename="{filename}"'
return response
这样,前端应该立即触发下载提示,并且文件将在后台分块流式传输。用户将在浏览器中看到下载进度,并且无需等待整个文件下载完毕即可出现“保存”对话框。
请记住调整
file_path
和 filename
变量以匹配您的实际文件详细信息。