Django:使用django-storage从S3创建zipfile

问题描述

我使用django-storages,并将与用户相关的内容存储在S3上的文件夹中。现在,我希望用户能够一次下载所有文件,最好是zip文件。以前与此相关的所有帖子都过时或不适合我。

到目前为止,我最接近的工作代码:

from io import BytesIO
import zipfile
from django.conf import settings
from ..models import Something
from django.core.files.storage import default_storage

class DownloadIncomeTaxFiles(View):

    def get(self,request,id):
        itr = Something.objects.get(id=id)
        files = itr.attachments
        zfname = 'somezip.zip'
        b =  BytesIO()
        with zipfile.ZipFile(b,'w') as zf:
            for current_file in files:
                try:
                    fh = default_storage.open(current_file.file.name,"r")
                    zf.writestr(fh.name,bytes(fh.read()))
                except Exception as e:
                    print(e)
            response = HttpResponse(zf,content_type="application/x-zip-compressed")
            response['Content-Disposition'] = 'attachment; filename={}'.format(zfname)
            return response

这会创建一个看起来像zipfile的文件,但是它唯一的内容是''

我得到了许多不同的结果,主要是由于提供了FieldFile时,诸如zipfile期望字符串或字节内容的错误。此时,我完全被卡住了。

解决方法

问题是我需要通过添加恢复到文件的开头

zf.seek(0)

就在返回HttpResponse中的文件之前。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...