![](/img/trans.png)
[英]why can't python unzip a password protected zip file created by winrar using the zip method?
[英]Can't open zip file created with python and Django
我創建了一組 pdf 文件,並希望將它們添加到 zip 存檔中。 一切似乎都很好,但是當我下載我的 zip 文件時,它無法打開。
所以我用create_pdf
function 創建 pdf
def create_pdf(child):
buffer = io.BytesIO()
canvas = Canvas(buffer, pagesize=A4)
p = staticfiles_storage.path('TNR.ttf')
pdfmetrics.registerFont(TTFont('TNR', p))
canvas.setFont('TNR', 14)
t = canvas.beginText(-1 * cm, 29.7 * cm - 1 * cm)
t.textLines(create_text(child), trim=0)
canvas.drawText(t)
canvas.save()
pdf = buffer.getvalue()
return pdf
然后我創建 zip 文件並將其打包以響應
def create_zip(pdfs):
mem_zip = io.BytesIO()
i = 0
with zipfile.ZipFile(mem_zip, mode='w', compression=zipfile.ZIP_DEFLATED)\
as zf:
for f in pdfs:
i += 1
zf.writestr(f'{str(i)}.pdf', f)
return mem_zip.getvalue()
def get_files(request, children):
pdfs = []
for child in children:
pdfs.append(create_pdf(child))
zip = create_zip(pdfs)
response = FileResponse(zip,
content_type='application/zip',
filename='zayavleniya.zip')
response['Content-Disposition'] = 'attachment; filename=files.zip'
return response
請幫助找出我錯在哪里。
在文檔中,您可以看到write_str
方法需要data
作為第二個參數。 在這里,您提供了一個文件名。 所以 pdf 文件的內容只是“i.pdf”,這當然不是您期望的 pdf 文件的內容。
嘗試這樣的事情:
def create_zip(pdfs):
mem_zip = io.BytesIO()
i = 0
with zipfile.ZipFile(mem_zip, mode='w', compression=zipfile.ZIP_DEFLATED)\
as zf:
for filename in pdfs:
i += 1
with open(filename, 'rb') as f:
zf.writestr(f'{i}.png', f.read())
return mem_zip.getvalue()
注意:盡量避免使用
zip
作為變量名,因為它已經是內置 python function
如果您隔離存檔創建以獲得最小的工作示例,您會得到這個,它會根據需要創建一個 zipfile:
def create_zip(pdfs):
i = 0
with zipfile.ZipFile(HERE / "my_archive.zip", mode='w', compression=zipfile.ZIP_DEFLATED)\
as zf:
for filename in pdfs:
i += 1
with open(filename, 'rb') as f:
zf.writestr(f'{str(i)}.png', f.read())
create_zip(["icon.png"])
在我發布這個問題之后,我設法自己找到了答案。 我改變了create_zip
def create_zip(pdfs):
mem_zip = io.BytesIO()
i = 0
with zipfile.ZipFile(mem_zip, mode='w', compression=zipfile.ZIP_DEFLATED)\
as zf:
for f in pdfs:
i += 1
zf.writestr(f'{str(i)}.pdf', f)
mem_zip.seek(0)
return mem_zip
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.