java 如何从 JSP 打开 pdf 文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6271708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to open a pdf document from JSP
提问by Dilllllo
How do I open a PDF document from JSP? I have many links to PDF files. In Eclipse, when I click on the link, the PDF opens in PDF reader. But in a webbrowser like Firefox and Chrome, nothing happens.
如何从 JSP 打开 PDF 文档?我有很多指向 PDF 文件的链接。在 Eclipse 中,当我单击链接时,PDF 会在 PDF 阅读器中打开。但是在像 Firefox 和 Chrome 这样的网络浏览器中,什么也没有发生。
I am generating the links to PDF files as F:\....\...pdf
the following way:
我按F:\....\...pdf
以下方式生成 PDF 文件的链接:
<%
while (iter.hasNext()) {
element = iter.next();
bookName = getBookName(element);
%>
<ul>
<li><a href="<%=element %>"><%=bookName %></a>
</ul>
<%
}
%>
How is this problem caused and how can I solve it?
这个问题是如何引起的,我该如何解决?
回答by BalusC
The links have to point to an URL, not to a local disk file system path or something. The average webbrowser doesn't swallow this due to security restrictions. And even then when it did, it would not work in production environment when the webbrowser runs at a physically different machine than the webserver and thus doesn't have access to F:
disk at all.
这些链接必须指向一个 URL,而不是指向本地磁盘文件系统路径或其他东西。由于安全限制,一般的网络浏览器不会吞下这一点。即使这样,当 webbrowser 在与 web 服务器物理不同的机器上运行时,它也不会在生产环境中工作,因此根本无法访问F:
磁盘。
So, you should NOTuse
所以,你应该不使用
<a href="F:\....\...pdf">link</a>
but you should rather use
但你应该使用
<a href="http://example.com/filename.pdf">link</a>
or when it's for example in the same folder of the current JSP file
或者当它位于当前 JSP 文件的同一文件夹中时
<a href="filename.pdf">link</a>
If you cannot put the PDF file in your own web project, then you need to look for different solutions.
如果您无法将 PDF 文件放入您自己的 Web 项目中,那么您需要寻找不同的解决方案。
- Add the external folder as another context of the servletcontainer.
- Move the external folder into deploy folder of the servletcontainer.
- Create a servlet which reads it from disk and writes it to response.
- 添加外部文件夹作为 servletcontainer 的另一个上下文。
- 将外部文件夹移动到 servlet 容器的部署文件夹中。
- 创建一个从磁盘读取它并将其写入响应的 servlet。
You can find the above solutions in detail in the answers of the following questions:
您可以在以下问题的答案中详细找到上述解决方案: