4

I'm trying to serve a PDF file with django 1.7, and this is basically the code that "should" work... it certainly works if I change the content_type to 'text' and download a .tex file with it, but when I try it with a binary file, I get "UnicodeDecodeError at /path/to/file/filename.pdf 'utf-8' codec can't decode byte 0xd0 in position 10: invalid continuation byte"

def download(request, file_name):
    file = open('path/to/file/{}'.format(file_name), 'r')
    response = HttpResponse(file, content_type='application/pdf')
    response['Content-Disposition'] = "attachment; filename={}".format(file_name)
    return response

So basically, if I understand correctly, it's trying to serve the file as a UTF-8 encoded text file, instead of a binary file. I've tried to change the content_type to 'application/octet-stream' with similar results. What am I missing?

Joonas Joensuu
  • 102
  • 2
  • 10
  • You haven't read the file; you're now passing a file pointer to `HttpResponse`, not the PDF data. –  Jan 28 '15 at 11:04

1 Answers1

11

Try opening the file using binary mode:

file = open('path/to/file/{}'.format(file_name), 'rb')
Jon S.
  • 1,378
  • 8
  • 14