2013-07-18 177 views
0

我想从服务器下载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内。不知道什么是错误的。如果有人能帮助我,我会很感激。

在此先感谢。

+0

你试过调试吗?你可以验证文件正在从磁盘读取,并确实发送回响应? – mthmulders

+1

此外,为了提高性能,使用'byte []'而不是每次读/写一个字节可能会很有趣。 – mthmulders

+0

您应该在finally块中关闭输入流。如果出于某种原因而导致I/O错误,并且未达到close(),则会泄漏文件描述符 – fge

回答

0

试着改变你的代码是这样的:

response.setContentType("application/force-download"); 
File f = new File ("D:\\abc.pdf"); 
response.addHeader("Content-Disposition", "attachment; filename=\"abc.pdf\""); 
InputStream inputStream = new FileInputStream(f); 
BufferedOutputStream out = 
       new BufferedOutputStream(response.getOutputStream()); 
byte by[] = new byte[32768]; 
int index; 
if (inputStream != null) { 
    index = inputStream.read(by, 0, 32768); 
} else { 
    index = -1; 
} 
while (index != -1) { 
    out.write(by, 0, index); 
    index = inputStream.read(by, 0, 32768); 
} 
out.flush(); 
+0

感谢MaVRoSCy的回复,但是它对我的工作, response.setContentType(“application/force-download”); 在控制台中出现错误。 – user2594235

+0

你是什么意思'越来越错了'有什么异常?该行不应该导致任何问题 – MaVRoSCy

+0

[永远不要使用该黑客:@](http://stackoverflow.com/a/10616753/1654265)...“Content-Disposition:attachment”足以确保文件被询问下载,或威胁的方式浏览器的设置由用户配置(总是打开,总是下载等) –

0

更改这个密码。注意输入流的处理:它是在I/O错误的情况下,正确关闭:

final byte[] buf = new byte[16384]; 
int count; 

final InputStream in = new FileInputStream(...); 
final OutputStream out = servlet.getOutputStream(); 

try { 
    while ((count = in.read(buf)) != -1) 
     out.write(buf, 0, count); 
    out.flush(); 
} catch (...) { 
} finally { 
    in.close(); 
} 

如果你能负担得起,用番石榴和Closer处理I/O资源。

0

对于Liferay,有一个sample-struts portlet,其中包含未嵌入完整门户页面的下载自定义类型 - 例如,内容类型可能与通常的门户网站的HTML不同。在this example它是图像/ jpeg。根据你的问题应用这个。