我想从服务器下载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>
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内。不知道什么是错误的。如果有人能帮助我,我会很感激。
在此先感谢。
你试过调试吗?你可以验证文件正在从磁盘读取,并确实发送回响应? – mthmulders
此外,为了提高性能,使用'byte []'而不是每次读/写一个字节可能会很有趣。 – mthmulders
您应该在finally块中关闭输入流。如果出于某种原因而导致I/O错误,并且未达到close(),则会泄漏文件描述符 – fge