是否可以显示 PDF 文件inDjango 视图,而不是让用户必须下载它才能看到它?
如果可能的话,会怎样做?
这就是我到目前为止所拥有的 -
@login_required
def resume(request, applicant_id):
#Get the applicant's resume
resume = File.objects.get(applicant=applicant_id)
fsock = open(resume.location, 'r')
response = HttpResponse(fsock, mimetype='application/pdf')
return response
Django有一个专门用于返回文件的类,文件响应 https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.FileResponse。它流式传输文件,这样您就不必在返回文件之前将整个文件读入内存。干得好:
from django.http import FileResponse, Http404
def pdf_view(request):
try:
return FileResponse(open('foobar.pdf', 'rb'), content_type='application/pdf')
except FileNotFoundError:
raise Http404()
如果您有非常大的文件或者经常这样做,更好的选择可能是使用正常的服务器配置在 Django 之外提供这些文件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)