通过Django链接发送PDF时出错



这里是Django的新手。我尝试使用此代码成功发送CSV,但在发送我使用matplotlib 生成的pdf文件时出现以下错误

UnicodeDecodeError:"utf-8"编解码器无法解码位置中的字节0xac10:起始字节无效

这是代码

def download_file(request):
# fill these variables with real values
fl_path = 'file.pdf'
filename = 'report.pdf' 
fl = open(fl_path, 'r', encoding='utf-8')
mime_type, _ = mimetypes.guess_type(fl_path)
print(mime_type)
response = HttpResponse(fl, content_type=mime_type)
response['Content-Disposition'] = "attachment; filename=%s" % filename
return response

有没有办法知道我需要通过哪个正确的编码来发送文件?

使用django的FileResponse而不是HttpResponse,FileResponse更适合发送文件数据。

return FileResponse(fl, filename=''.format(filename ), as_attachment=True,
content_type='application/pdf')

最新更新