import os, tempfile, zipfile
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
def send_file(request):
"""
Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for chunks of 8KB.
"""
filename = __file__ # Select your file here.
wrapper = FileWrapper(file(filename))
response = HttpResponse(wrapper, content_type='text/plain')
response['Content-Length'] = os.path.getsize(filename)
return response
def send_zipfile(request):
"""
Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files.
"""
temp = tempfile.TemporaryFile()
archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
for index in range(10):
filename = __file__ # Select your files here.
archive.write(filename, 'file%d.txt' % index)
archive.close()
wrapper = FileWrapper(temp)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=test.zip'
response['Content-Length'] = temp.tell()
temp.seek(0)
return response
Comments
For people on Windows you'll need to specify "read binary" mode for anything other than a text file:
#
As far as I know this is the only way to get password protection for files when you are using Django under FCGI (and I assume CGI and SCGI). For people using mod_python, mod_wsgi there are better solutions.
It would be good to get all this protected or dynamic file download info into one place.
#
Andy, you are saying there are better solutions for people using mod_wsgi? -- Can you list them?
#
Currently this seems to be broken in latest svn? -- I disabled the conditional GET middlewhere and gzip middlewhere and when I pass a FileWrapper to HttpResponse, it returns a page with content-length 0.
#
Not being able to get this working on latest SVN, I've went with this approache instead: http://tn123.ath.cx/mod_xsendfile/ -- this is an apache model but I believe it's built into lighttpd and others. Details of this and other methods available here: http://code.djangoproject.com/ticket/2131
#
some code in gzip middleware, which like "len(response.content)" will read the FileWrapper, so after that content length is 0.
Maybe edit gzip middleware, then use your own gzip in settings.py
some examples code: https://github.com/akun/dj-download
#
Got this working with a few tweaks:
#
and the solution, FixedFileWrapper, at https://code.djangoproject.com/ticket/6027 worked for my purposes
#
@theviaxx
FixedFileWrapperworks for me. Thanks for sharing.#