Generating file to download with Django


Question

Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?

1
95
5/25/2009 10:26:01 PM

To trigger a download you need to set Content-Disposition header:

from django.http import HttpResponse
from wsgiref.util import FileWrapper

# generate the file
response = HttpResponse(FileWrapper(myfile.getvalue()), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=myfile.zip'
return response

If you don't want the file on disk you need to use StringIO

import cStringIO as StringIO

myfile = StringIO.StringIO()
while not_finished:
    # generate chunk
    myfile.write(chunk)

Optionally you can set Content-Length header as well:

response['Content-Length'] = myfile.tell()
111
7/27/2016 9:16:30 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon