如何在django中提供可下载的zip文件 [英] how to serve downloadable zip file in django

查看:149
本文介绍了如何在django中提供可下载的zip文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我去过django文档,我发现这段代码允许你将文件作为附件呈现。

Im going over the django documentation and I found this piece of code that allows you to render a file as attachment

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

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

The foo.zip file was created using pythons zipfile.ZipFile().writestr method

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()

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

But when I tried the code above to render the file, Im getting this error


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

'utf8' codec can't decode byte 0x89 in position 10: invalid start byte

有关如何执行此操作的任何建议?

Any suggestions on how to do this right?

推荐答案

我想你想要的是为人们提供一个文件来下载它。如果是这样,你不需要渲染文件,它不是一个模板,你只需要将其作为附件使用Django的HttpResponse

I think what you want is to serve a file for people to download it. If that's so, you don't need to render the file, it's not a template, you just need to 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

希望这个帮助!

这篇关于如何在django中提供可下载的zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆