如何在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
推荐答案
简单来说,如果你有一个PDF文件,你想输出通过Django视图,您需要做的是将文件内容转储到响应中并使用适当的mimetype发送。
Simplistically, if you have a PDF file and you want to output it through a Django view, all you need to do is dump the file contents into the response and send it with the appropriate mimetype.
def pdf_view(request):
with open('/path/to/my/file.pdf', 'r') as pdf:
response = HttpResponse(pdf.read(), mimetype='application/pdf')
response['Content-Disposition'] = 'inline;filename=some_file.pdf'
return response
pdf.closed
您可以直接返回响应而不指定Content-Disposition,但更好地表示您的意图,并且还允许您指定文件名,以防万一用户决定保存它。
You can probably just return the response directly without specifying Content-Disposition, but that better indicates your intention and also allows you specify the filename just in case the user decides to save it.
另外,请注意,上面的视图不会处理由于某种原因无法打开或读取文件的场景。由于它使用与
完成,它不会引发任何异常,但您仍然必须返回某种响应。不过,您可以简单地提出一个 Http404
或
Also, note that the view above doesn't handle the scenario where the file cannot be opened or read for whatever reason. Since it's done with with
, it won't raise any exceptions, but you still must return some sort of response. You could simply raise an Http404
or something, though.
这篇关于如何在Django视图中显示PDF文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!