Django 利用zipstream壓縮下載多文件夾

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
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章