接收请求地址下载并输出文件流实现

代码:

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请求头,方便在下载文件时告诉服务器要将其视为附件,并给定一个文件名。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值