Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error sending a file using Django - file turns out empty

This is my views.py files:

from django.http import HttpResponse

def render(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
    response['X-Sendfile'] = '/files/filename.pdf'
    # path relative to views.py
    return response

When I run the server and request

http://localhost:8080/somestring

I get an empty file called somefilename.pdf. I suspect that there is some crucial part missing in render.

The other parts of this app outside of views.py are correct to my understanding.

like image 741
Clone Avatar asked Oct 26 '25 14:10

Clone


1 Answers

Here is the code that solved my problem:

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

def render(request): 
    response = HttpResponse(FileWrapper(open('file.pdf', 'rb')), content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

    return response
like image 185
Clone Avatar answered Oct 29 '25 06:10

Clone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!