使用 Django 作为附件输出 PDF 并重新加载
我正在使用 django 生成 pdf 并将响应作为视图中的附件返回。
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
类似于文档 (http:// /docs.djangoproject.com/en/dev/howto/outputting-pdf/#write-your-view)
重新加载页面的最佳方法是什么?
这没有成功(表单触发了 pdf 生成):
$('#the_form').submit(function(){
location.reload();
});
非常感谢, 丹尼
I´m using django to generate a pdf and return the response as an attachment in the view.
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
Similar to the way described in the doc (http://docs.djangoproject.com/en/dev/howto/outputting-pdf/#write-your-view)
What is the best way to reload the page?
This didn´t work out (the form triggers the pdf generation):
$('#the_form').submit(function(){
location.reload();
});
Thanks a lot,
Danny
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要重新加载。相反,创建一个作为表单目标的视图。该视图在从真实 Web 服务器传送的目录中生成 PDF,然后将用户发送到适当的 URL,用户可以在其中下载文件(使用 HttpResponseRedirect)。
Don't reload. Instead create a view which is the target of the form. The view generates the PDF in a directory that is delivered from the real web server and then sends the user to the appropriated URL, where he can download the file (use HttpResponseRedirect).
只需将表单目标设置为生成 pdf 的视图即可。下面我列出了这种方法与 Martin 建议的方法(将文件写入世界可以读取的目录)的一些优点和缺点
优点:
:
-
另一个解决方案是使用网络服务器的 X-SendFile 标头。在谷歌上搜索您的特定服务器的说明。总体思路是,您的视图为网络服务器提供了一个文件路径,然后网络服务器将直接从磁盘读取该文件并将其返回给用户。您甚至可以“强制下载”这些文件,请查看您的网络服务器的文档以了解如何执行此操作。
Just set the forms target to the view that generates the pdf. Below I included some pros and cons for this approach vs the approach suggested by Martin (to write files to a directory the world can read)
Pros:
Cons:
--
Another solution would be to use the X-SendFile header of your webserver. Do a google search for instructions for your particular server. The general idea is that your view gives the webserver a path to a file which the webserver will then read directly from disk and return to the user. You can probably "force download" even these files, have a look at the documentation for your webserver on how to do it.