Python/Django:提供一个可从io.BytesIO缓冲区下载的zip文件 [英] Python/Django: Offering a zip file for download from io.BytesIO buffer
本文介绍了Python/Django:提供一个可从io.BytesIO缓冲区下载的zip文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将zip文件放入io.BytesIO缓冲区中,然后提供该文件以供下载.以下是我所拥有的(更长的views.py的一部分,我只是在发布相关部分).
I'm trying to put a zip file into an io.BytesIO buffer and then offer that for download. Below is what I've got (part of a longer views.py, I'm just posting the relevant part).
但是我收到以下错误消息:
AttributeError at 'bytes' object has no attribute 'read'
有人可以告诉我我在做什么错吗?
from django.http import HttpResponse
from wsgiref.util import FileWrapper
from zipfile import *
import io
buffer = io.BytesIO()
zipf = ZipFile(buffer, "w")
zipf.write ("file.txt")
zipf.close()
response = HttpResponse(FileWrapper(buffer.getvalue()), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=file.zip'
return response
告诉我错误来自以下行:
It's telling me the error is coming from the line:
response = HttpResponse(FileWrapper(buffer.getvalue()), content_type='application/zip')
推荐答案
您需要以字节模式('b')
尝试更改
buffer = io.BytesIO()
zipf = ZipFile(buffer, "w")
zipf.write ("file.txt")
zipf.close()
到
zipf = zipfile.ZipFile("hello.zip", "w")
zipf.write("file.txt")
zipf.close()
response = HttpResponse(io.open("hello.zip", mode="rb").read(), content_type='application/zip')
这篇关于Python/Django:提供一个可从io.BytesIO缓冲区下载的zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文