我有一个方法可以生成 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
目录中留下的一些秘密报告吗?
你不能像这样通过HTTP访问服务器的文件系统。您需要的是一个由浏览器调用的 servlet,它读取 PDF 文件并在 HTTP 响应中发送它。
我看到其他人已经回答了您的结果,但我发现您很难理解他们的答案。好吧,那我就从更简单的事情开始吧。
只需在您的网页(站点根)目录中创建一个名为
/temp
的文件夹,然后放入 PDF (report.pdf
),该链接即可使用。
现在您所要做的就是使用简单的文件 IO 将报告放入该文件中。
例如如果您编写代码在
xyz.pdf
目录(已在您的 Web 根目录中可用)中编写名为 temp
的 PDF 文件,则访问 URL 将是 /temp/xyz.pdf
。
这是一个关于如何使用 struts2 下载文件的小快速 示例。
stream
结果的操作。
使用 struts2 下载文件的示例。您所需要做的就是将其应用到您的场景中。