1、安装 zipstream

pip install zipstream

2、简单封装下zipstream

# -*- coding: UTF-8 -*-
import zipfile
import os
import zipstream
class ZipUtilities:
    zip_file = None

    def __init__(self):
        self.zip_file = zipstream.ZipFile(mode='w', compression=zipstream.ZIP_DEFLATED)

    def toZip(self, file, name):
        if os.path.isfile(file):
            self.zip_file.write(file, arcname=os.path.basename(file))
        else:
            self.addFolderToZip(file, name)

    def addFolderToZip(self, folder, name):
        for file in os.listdir(folder):
            full_path = os.path.join(folder, file)
            if os.path.isfile(full_path):
                self.zip_file.write(full_path, arcname=os.path.join(name, os.path.basename(full_path)))
            elif os.path.isdir(full_path):
                self.addFolderToZip(full_path, os.path.join(name, os.path.basename(full_path)))

    def close(self):
        if self.zip_file:
            self.zip_file.close()

3、views.py 使用

utilities = ZipUtilities()
for file_obj in file_objs:
   tmp_dl_path = os.path.join(path_to, filename)
   utilities.toZip(tmp_dl_path, filename)
#utilities.close()
response = StreamingHttpResponse(utilities.zip_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment;filename="{0}"'.format("下载.zip")
return response


作者:huarda
链接:https://www.jianshu.com/p/398e22b34553
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐