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中的文件之前。