【发布时间】:2013-07-18 06:49:16
【问题描述】:
我想从服务器下载一个 pdf 文件。我正在使用tomcat。并在 struts2 中开发应用程序。
在我的jsp代码中,下载链接如下:
<td>
<a href='<s:url action='downloadPdf'> </s:url>'>
Download PDF</a>
</td>
我的 struts.xml 是:
<action name="downloadPdf" class="com.stp.portal.view.SearchServicePortlet" method="downloadPdf">
</action>
动作类是:
public void downloadPdf() throws Exception
{
HttpServletResponse response = null;
try
{
response.setContentType ("application/pdf");
File f = new File ("D:\\abc.pdf");
response.setHeader ("Content-Disposition", "attachment;filename=abc.pdf");
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);
}
}
catch (Exception ioe)
{
ioe.printStackTrace(System.out);
}
servletOutputStream.flush();
inputStream.close();
}
catch(Exception e)
{
}
}
public String generateGraph() throws Exception
{
return "success";
}
}
我的问题是当我单击下载链接时,文件未下载。 abc.pdf文件在本地D盘里面。不知道哪里出了问题。如果有人可以帮助我,我将不胜感激。
提前致谢。
【问题讨论】:
-
你试过调试吗?您能否验证文件是否正在从磁盘读取并确实发送回响应?
-
此外,为了提高性能,使用
byte[]而不是一次读取/写入一个字节可能会很有趣。 -
你应该在 finally 块中关闭你的输入流。如果由于某种原因出现 I/O 错误并且未达到 close(),则您会泄漏文件描述符
-
我试过调试,但什么都没有,没有错误
-
您使用的是 Java 7 还是 Java 6?