如何在 Django 视图中显示 PDF 文件? [英] How to show a PDF file in a Django view?
问题描述
是否可以在 Django 视图中显示 PDF 文件,而不是让用户必须下载才能查看?
Is it possible to show a PDF file in the Django view, rather than making the user have to download it to see it?
如果可能的话,会怎么做?
And if it is possible, how would it be done?
这是我目前所拥有的 -
This is what I have so far -
@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 有一个专门用于返回文件的类,文件响应.它流式传输文件,因此您不必在返回之前将整个文件读入内存.给你:
Django has a class specifically for returning files, FileResponse. It streams files, so that you don't have to read the entire file into memory before returning it. Here you go:
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 之外提供这些文件.
If you have really large files or if you're doing this a lot, a better option would probably be to serve these files outside of Django using normal server configuration.
这篇关于如何在 Django 视图中显示 PDF 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!