[Fixed]-How to send file to response in Django?

23πŸ‘

βœ…

Read file first and then send it in response.

from django.http import HttpResponse, HttpResponseNotFound

def waprfile(request, date):
    ...

    file_location = '/path/to/file/foo.xls'

    try:    
        with open(file_location, 'r') as f:
           file_data = f.read()

        # sending response 
        response = HttpResponse(file_data, content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename="foo.xls"'

    except IOError:
        # handle file not exist case here
        response = HttpResponseNotFound('<h1>File not exist</h1>')

    return response

Read docs for more info:
telling browser to treat the response as a file attachment and returning errors

πŸ‘€Satendra

3πŸ‘

To return a PDF file in response in Django, use below code.

def index(request):
    data = dict()
    data["name"] = "https://www.pythoncircle.Com"
    data["DOB"] = "Jan 10, 2015"

    template = get_template('testapp/test.html')
    html = template.render(data)
    pdf = pdfkit.from_string(html, False)

    filename = "sample_pdf.pdf"

    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="' + filename + '"'
    return response

[1] https://www.pythoncircle.com/post/470/generating-and-returning-pdf-as-response-in-django/

πŸ‘€Anurag Rana

1πŸ‘

If you want to return an image don’t forget to format it as png or jpeg and return the bytes with getvalue()

img = "Suppose I am a pil image"
fomatted_img = BytesIO()
img.save(fomatted_img, format="png")
response = HttpResponse(fomatted_img.getvalue(),content_type='image/png')
response['Content-Disposition'] = 'attachment; filename="output.png"'
return response

Or you can save the formatted image directly into the response

img = "Suppose I am a pil image"
response = HttpResponse(content_type='image/png')
response['Content-Disposition'] = 'attachment; filename="output.png"'
img.save(response,"PNG")
return response

Leave a comment