Generating File to Download with Django

How to download a dynamic file in django?

You can write a streamed response like you can see in the django docs

In your case it might do something like this with your file;

import csv

from django.http import StreamingHttpResponse

class Echo:
"""An object that implements just the write method of the file-like
interface.
"""
def write(self, value):
"""Write the value by returning it, instead of storing in a buffer."""
return value

def some_streaming_csv_view(request):
""" A view that streams a large CSV file. """
data = open(path,'r').readlines()

pseudo_buffer = Echo()
writer = csv.writer(pseudo_buffer)
response = StreamingHttpResponse(
(writer.writerow(row) for row in data),
content_type="text/csv"
)
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
return response

Add the GET param to your URL, because you're already adding it to the context and trying to read it back out;

<p><a href ="{% url 'download' %}?path={{ path|urlencode }}">Download (Filename)</a></p>

django download generated file

May be you should send the file as a chunk , which is memory efficient

import os
import mimetypes
from django.http import StreamingHttpResponse
from wsgiref.util import FileWrapper

def download_file(request):
the_file = open(file_path, "rb")
filename = os.path.basename(the_file)
chunk_size = 8192
response = StreamingHttpResponse(FileWrapper(open(the_file, 'rb'), chunk_size),
content_type=mimetypes.guess_type(the_file)[0])
response['Content-Length'] = os.path.getsize(the_file)
response['Content-Disposition'] = "attachment; filename=%s" % filename
return response

Django download a file

You missed underscore in argument document_root. But it's bad idea to use serve in production. Use something like this instead:

import os
from django.conf import settings
from django.http import HttpResponse, Http404

def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404

Django: Cannot download generating file

Because in your case f.read() is returning an empty string, you have to manually move the file pointer at the beginning of the file in order to read the content after writing

def report_generate(request):
f = open("test.txt", "w+")
for i in range(10):
f.write("This is line %d\r\n" % (i + 1))
f.seek(0) # Move the pointer at the beginning
response = HttpResponse(f.read(), content_type='text/plain')
f.close() # Close the file
filename = "guru99.txt"
response['Content-Disposition'] = 'attachment; filename="%s"' % filename
return response


Related Topics



Leave a reply



Submit