Django 1.7: serve a pdf -file (UnicodeDecodeEr

2019-06-25 09:54发布

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?

1条回答
爷、活的狠高调
2楼-- · 2019-06-25 10:27

Try opening the file using binary mode:

file = open('path/to/file/{}'.format(file_name), 'rb')
查看更多
登录 后发表回答