[英]Can't open zip file created with python and Django
I create a set of pdf files and want to add them to zip archive.我创建了一组 pdf 文件,并希望将它们添加到 zip 存档中。 Everything seems fine, but when I download my zip file It can't be open.
一切似乎都很好,但是当我下载我的 zip 文件时,它无法打开。
So I create pdf with create_pdf
function所以我用
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
Then I create zip file and pack it to response然后我创建 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
Please help to find where I am wrong.请帮助找出我错在哪里。
In the documentation , you can see the write_str
method expects data
as second argument.在文档中,您可以看到
write_str
方法需要data
作为第二个参数。 Here, you are providing a filename.在这里,您提供了一个文件名。 So the content of the pdf files are just "i.pdf", which is of course not the content that you expect for a pdf file.
所以 pdf 文件的内容只是“i.pdf”,这当然不是您期望的 pdf 文件的内容。
Try with something like this:尝试这样的事情:
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()
NB: try to avoid using
zip
as a variable name, since it is already a builtin python function注意:尽量避免使用
zip
作为变量名,因为它已经是内置 python function
If you isolate the archive creation to get a minimal working example, you get this, which create an zipfile as you wanted:如果您隔离存档创建以获得最小的工作示例,您会得到这个,它会根据需要创建一个 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"])
After I post this question I managed to find the answer myself.在我发布这个问题之后,我设法自己找到了答案。 I changed
create_zip
我改变了
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.