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?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With