我使用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。在这一点上,我完全卡住了。
发布于 2020-08-25 17:54:48
问题是我需要恢复到文件的开头,方法是添加
zf.seek(0)就在返回HttpResponse中的文件之前。
https://stackoverflow.com/questions/63566438
复制相似问题