代码:
import httpx
from datetime import datetime
from io import BytesIO
from fastapi.responses import StreamingResponse
@router.get("/download", tags=["下载···"])
async def file_download(str_url: str):
file_name = datetime.now().strftime('%Y%m%d%H%M%S%f')
content_disposition = f"attachment; filename*=utf-8 {file_name}"
headers = {'Content-Disposition': content_disposition}
async with httpx.AsyncClient() as client:
response = await client.get(str_url)
if response.status_code == 200:
return StreamingResponse(BytesIO(response.content), headers=headers, media_type='application/octet-stream')
else:
raise http_400_exception(f"Failed to download file from {str_url}")
代码解析:
content_disposition 创建一个字符串content_disposition,用于设置HTTP响应头中的Content-Disposition字段。通过这个字段告诉浏览器将响应内容视为附件,并给这个附件一个名字,就是file_name。
headers = {‘Content-Disposition’: content_disposition}:创建一个字典headers,字典键Content-Disposition用于设置HTTP请求头,方便在下载文件时告诉服务器要将其视为附件,并给定一个文件名。