Joo*_*suu 4 python binaryfiles python-3.4 django-1.7
我正在尝试使用django 1.7提供PDF文件,这基本上是"应该"工作的代码......如果我将content_type更改为'text'并使用它下载.tex文件,它肯定有效,但是我用二进制文件尝试它,我得到"/Dev/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
Run Code Online (Sandbox Code Playgroud)
所以基本上,如果我理解正确,它会尝试将文件作为UTF-8编码的文本文件而不是二进制文件.我试图将content_type更改为'application/octet-stream',结果类似.我错过了什么?
小智 11
尝试使用二进制模式打开文件:
file = open('path/to/file/{}'.format(file_name), 'rb')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1210 次 |
| 最近记录: |