how to serve downloadable zip file in django

2019-04-29 18:44发布

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

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' codec can't decode byte 0x89 in position 10: invalid start byte

Any suggestions on how to do this right?

1条回答
再贱就再见
2楼-- · 2019-04-29 19:31

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

Hope this helps!

查看更多
登录 后发表回答