Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to serve downloadable zip file in 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

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?

like image 485
helloworld2013 Avatar asked Oct 18 '13 21:10

helloworld2013


2 Answers

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
like image 158
Paulo Bu Avatar answered Sep 28 '22 07:09

Paulo Bu


FileResponse is preferred over HttpResponse for binary files. Also, opening the file in 'rb' mode prevents UnicodeDecodeError.

zip_file = open(path_to_file, 'rb')
return FileResponse(zip_file)
like image 21
xtranophilist Avatar answered Sep 28 '22 07:09

xtranophilist