how to serve downloadable zip file in django

16,141

Solution 1

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

Solution 2

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)
Share:
16,141
helloworld2013
Author by

helloworld2013

Updated on June 04, 2022

Comments

  • helloworld2013
    helloworld2013 almost 2 years

    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?

  • helloworld2013
    helloworld2013 over 10 years
    Just a question about this solution, does python's open() automatically close after scope? With this you cannot close the stream until you return it to make it work. Thanks.
  • helloworld2013
    helloworld2013 over 10 years
  • Paulo Bu
    Paulo Bu over 10 years
    @helloworld2013: Sorry man I wasn't online. I guess you already answered your question :). (In a nutshell) when the zip_file gets out of scope and garbage collection do its thing, the resources for the file will be released.
  • Scratcha
    Scratcha almost 4 years
    This worked beautifully for me. See docs.djangoproject.com/en/3.0/ref/request-response/… for more parameters such as specifying a target file name.