Clone
Clone

Reputation: 3648

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.

Upvotes: 4

Views: 664

Answers (2)

Clone
Clone

Reputation: 3648

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

Upvotes: 2

Alasdair
Alasdair

Reputation: 308839

The manage.py runserver development serer doesn't support X-Sendfile. In production, you need to enable X-Sendfile for your server (e.g. Apache).

You may find the django-sendfile package useful. It has a backend that you can use in development. However, it hasn't had a release in some time, and I found that I had to apply pull request 62 to get Python 3 support.

Upvotes: 0

Related Questions