Django 1.7: serve a pdf -file (UnicodeDecodeError)

倖福魔咒の 提交于 2019-12-10 15:58:05

问题


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:


Try opening the file using binary mode:

file = open('path/to/file/{}'.format(file_name), 'rb')


来源:https://stackoverflow.com/questions/28190318/django-1-7-serve-a-pdf-file-unicodedecodeerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!