我有一个生成 PDF 文件并将其存储在 /temp
文件夹中的方法。我正在使用汤姆猫。我想打开 PDF 文件。我在 JavaScript 中使用 window.open()
方法尝试过这个。但是在点击超链接时它说找不到请求的资源。
我使用以下行将 PDF 文件存储在 /temp
文件夹中(当然文件会生成并保存在该位置):
inputMap.put(TableProperties.PDF_PATH, "/temp/report.pdf");
现在在 JSP 中我尝试以下操作:
<tr>
<td>
<a href="" onclick="javascipt:window.open('/temp
/report.pdf');" class="popup">Click to open.</a>
</td>
</tr>
但它显示以下错误:
The requested resource was not found.
http://localhost:8080/temp/report.pdf
编辑:
尝试了以下方法:
在 JSP 页面中,打开文件的下载链接:
<tr>
<td>
<a href='<s:url action='gotoDownloadPdf'> </s:url>'>
download
</a>
</td>
</tr>
在struts.xml
中:
<action name="gotoDownloadPdf" class="com.stp.portal.view.SearchServicePortlet" method="gotoDownloadPdf">
<result name="success">/WEB-INF/view/pdfDownload.jsp</result>
</action>
包含用于下载 PDF 文件的 JavaScript 的 JSP 页面:
<%@ page import="java.util.*,java.io.*"%>
<%@ page language="java"%>
<!--Assumes that file name is in the request objects query Parameter -->
<%
//response.setHeader ("Cache-Control","no-cache");
//response.setHeader ("Pragma","no-cache");
//response.setHeader ("Expires",0);
//read the file name.
try
{
String fpath="/temp/";
String fileName="report.pdf";
fpath = fpath + fileName;
String fileType="pdf";
File f = new File (fpath);
//set the header and also the Name by which user will be prompted to save
response.setHeader ("Content-Disposition", "attachment;filename=\""+fileName+"\"");
//get the file name
String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
//OPen an input stream to the file and post the file contents thru the
//servlet output stream to the client m/c
InputStream inputStream = new FileInputStream(f);
ServletOutputStream servletOutputStream = response.getOutputStream();
int bit = 256;
int i = 0;
try
{
while ((bit) >= 0)
{
bit = inputStream.read();
servletOutputStream.write(bit);
}
//System.out.println("" +bit);
}
catch (Exception ioe)
{
//ioe.printStackTrace(System.out);
}
System.out.println( "\n" + i + " bytes sent.");
System.out.println( "\n" + f.length() + " bytes sent.");
servletOutputStream.flush();
//outs.close();
inputStream.close();
}
catch(Exception e)
{
}
%>
现在当我点击下载链接时,没有任何反应,它重定向到 JSP 页面,但是没有出现下载的弹出窗口。
最佳答案
想想你在做什么。你真的认为在浏览器地址栏中输入 http://www.google.com/tmp/secretReport.pdf
会让你访问 /tmp< 中的一些 secret 报告吗
谷歌服务器文件系统上的目录?
您不能像这样通过 HTTP 访问服务器的文件系统。您需要的是一个由浏览器调用的 servlet,它读取 PDF 文件并在 HTTP 响应中发送它。
关于java - 使用 window.open() 打开 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18161332/