01.import os, tempfile, zipfile
02.from django.http import HttpResponse
03.from django.core.servers.basehttp import FileWrapper
04.
05.
06.def send_file(request):
07. """
08. Send a file through Django without loading the whole file into
09. memory at once. The FileWrapper will turn the file object into an
10. iterator for chunks of 8KB.
11. """
12. filename = __file__ # Select your file here.
13. wrapper = FileWrapper(file(filename))
14. response = HttpResponse(wrapper, content_type='text/plain')
15. response['Content-Length'] = os.path.getsize(filename)
16. return response
17.
18.
19.def send_zipfile(request):
20. """
21. Create a ZIP file on disk and transmit it in chunks of 8KB,
22. without loading the whole file into memory. A similar approach can
23. be used for large dynamic PDF files.
24. """
25. temp = tempfile.TemporaryFile()
26. archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
27. for index in range(10):
28. filename = __file__ # Select your files here.
29. archive.write(filename, 'file%d.txt' % index)
30. archive.close()
31. wrapper = FileWrapper(temp)
32. response = HttpResponse(wrapper, content_type='application/zip')
33. response['Content-Disposition'] = 'attachment; filename=test.zip'
34. response['Content-Length'] = temp.tell()
35. temp.seek(0)
36. return response
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zhangzhenhu/archive/2011/01/27/6165917.aspx