django 实现zip包下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class TaskCenterDownload(APIView):
 
    def get(self,request):
 
        file_path = str(BASE_DIR) + '\download_file\\main.zip'
        file_name = 'main'
       
        if not os.path.isfile(file_path):
            return HttpResponeseJson(code=400,message="Sorry but Not Found the File")
 
        def file_iterator(file_path, chunk_size=512):
            """
            文件生成器,防止文件过大,导致内存溢出
            :param file_path: 文件绝对路径
            :param chunk_size: 块大小
            :return: 生成器
            """
            with open(file_path, mode='rb') as f:
                while True:
                    c = f.read(chunk_size)
                    if c:
                        yield c
                    else:
                        break
 
        try:
            # 设置响应头
            # StreamingHttpResponse将文件内容进行流式传输,数据量大可以用这个方法(.pdf,.zip,.mp4等等什么样格式的文件都可以下载)
            response = StreamingHttpResponse(file_iterator(file_path))
            # 以流的形式下载文件,这样可以实现任意格式的文件下载
            response['Content-Type'] = 'application/octet-stream'
            # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
            response['Content-Disposition'] = 'attachment;filename={file_name}{format}'.format(
                file_name=file_name, format=".zip")
        except:
            return HttpResponeseJson(code=400,message="Sorry but Not Found the File")
 
            # 在这里千万记得return,否则不会出现下载
        return response

 

1
2
3
4
5
6
7
8
9
10
11
12
def HttpResponeseJson(data=None, code='200', message='success'):
    try:
        rep = {
            "code": str(code),
 
            "message": message,
            "data": data
        }
        return Response(rep)
    except Exception as e:
        logger.error(f'序列化json出错{e}')
        return Response({'message': '序列化json出错'})

 

posted @   乔小生1221  阅读(653)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示