首页 > 编程语言 >【python】后端文件流下载数据

【python】后端文件流下载数据

时间:2022-11-04 16:22:22浏览次数:43  
标签:文件 name python url file response 下载 size

后台实现下载接口

1.1 通过文件流下载
import os
import time
from django.http import StreamingHttpResponse


def download_file_blob(name, url):
    """
    :param name: 文件名称(带后缀)
    :param url: 文件路径
    :return: 解析后数据
    """
    # 文件读取
    # chunk_size 单次读写大小
    def file_iterator(file_name, chunk_size=5120):
        with open(file_name, 'rb') as file:
            while True:
                char_buffer = file.read(chunk_size)
                if char_buffer:
                    yield char_buffer
                else:
                    break
                # 下载限速
                # time.sleep(0.001)

    if os.path.exists(url):
        response = StreamingHttpResponse(file_iterator(url))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = f'attachment;filename={name}'
        # 设置下载文件总大小
        file_info = os.stat(url)
        response['Content-Length'] = file_info.st_size
        return response

    return None

标签:文件,name,python,url,file,response,下载,size
From: https://www.cnblogs.com/jessecheng/p/16858225.html

相关文章