【发布时间】:2015-03-27 05:43:50
【问题描述】:
我正在尝试使用 django 1.7 提供 PDF 文件,这基本上是“应该”工作的代码......如果我将 content_type 更改为“文本”并下载一个 .tex 文件,它肯定会工作。 ,但是当我尝试使用二进制文件时,我在 /path/to/file/filename.pdf 处得到“UnicodeDecodeError” 'utf-8' 编解码器无法解码位置 10 中的字节 0xd0:无效的继续字节”
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',结果相似。我错过了什么?
【问题讨论】:
-
你还没有读过文件;您现在将文件指针传递给
HttpResponse,而不是 PDF 数据。
标签: python binaryfiles python-3.4 django-1.7