[英]Django: Create zipfile from S3 using django-storage
我使用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 的東西,但它唯一的內容是 '<zipfile.ZipFile [closed]>'
我得到了許多不同的結果,主要是像 zipfile 在提供 FieldFile 時期望字符串或字節內容這樣的錯誤。 在這一點上,我完全被困住了。
問題是我需要通過添加來恢復到文件的開頭
zf.seek(0)
就在 HttpResponse 中返回文件之前。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.