Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.7: serve a pdf -file (UnicodeDecodeError)

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?

like image 617
Joonas Joensuu Avatar asked Dec 19 '22 07:12

Joonas Joensuu


1 Answers

Try opening the file using binary mode:

file = open('path/to/file/{}'.format(file_name), 'rb')
like image 59
Jon S. Avatar answered Dec 22 '22 01:12

Jon S.