如何在django中提供可下载的zip文件

时间:2013-10-18 21:26:37

标签: python django file web render

我浏览了django文档,我发现这段代码允许你将文件渲染为附件

dl = loader.get_template('files/foo.zip')
context = RequestContext(request)
response = HttpResponse(dl.render(context), content_type = 'application/force-download')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'foo.zip'
return response

foo.zip文件是使用pythons zipfile.ZipFile()。writestr方法

创建的。
zip = zipfile.ZipFile('foo.zip', 'a', zipfile.ZIP_DEFLATED)
zipinfo = zipfile.ZipInfo('helloworld.txt', date_time=time.localtime(time.time()))
zipinfo.create_system = 1
zip.writestr(zipinfo, StringIO.StringIO('helloworld').getvalue())
zip.close()

但是当我尝试上面的代码来渲染文件时,我得到了这个错误

  

'utf8'编解码器无法解码位置10中的字节0x89:无效的起始字节

有关如何做到这一点的任何建议吗?

2 个答案:

答案 0 :(得分:9)

我认为您想要的是为人们提供下载文件。如果是这样,你不需要渲染文件,它不是模板,你只需要serve it as attachment using Django's HttpResponse

zip_file = open(path_to_file, 'r')
response = HttpResponse(zip_file, content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'foo.zip'
return response

希望这有帮助!

答案 1 :(得分:1)

对于二进制文件,

FileResponse优于HttpResponse。另外,以'rb'模式打开文件会阻止UnicodeDecodeError

zip_file = open(path_to_file, 'rb')
return FileResponse(zip_file)