Django 1.7:提供pdf文件(UnicodeDecodeError) [英] Django 1.7: serve a pdf -file (UnicodeDecodeError)

查看:42
本文介绍了Django 1.7:提供pdf文件(UnicodeDecodeError)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用django 1.7来提供PDF文件,这基本上是应该"工作的代码...如果我将content_type更改为文本"并下载一个.tex文件,它当然可以工作,但是当我尝试使用二进制文件时,在/path/to/file/filename.pdf处出现"UnicodeDecodeError" 'utf-8'编解码器无法解码位置10的字节0xd0:无效的继续字节"

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

因此,基本上,如果我理解正确,它将尝试将文件作为UTF-8编码的文本文件而不是二进制文件.我试图将content_type更改为"application/octet-stream",结果类似.我想念什么?

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?

推荐答案

尝试使用二进制模式打开文件:

Try opening the file using binary mode:

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

这篇关于Django 1.7:提供pdf文件(UnicodeDecodeError)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆