// 下载其实非常简单,只要如下处理,就不会发生问题。 public static void downLoad(String filePath, HttpServletResponse response,
boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0; response.reset(); // 非常重要
if (isOnLine) { // 在线打开方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename="
+ f.getName());
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType("application/x-msdownload;charset=gbk");
response.setHeader("Content-Disposition", "attachment; filename="
+ f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}

解决方案 »

  1.   

     public void downloadAction(ActionEvent event) {
        try {
          String fileName="D:\\temp\\images\\products\\" + this.id + ".xls";
          logger.debug("file name=" + fileName);
          ByteArrayOutputStream baos=this.serviceLocator.getFileService().downloadFile(fileName); //调用Service方法,获得文件的ByteArrayOutputStream
          HttpServletResponse response=FacesUtils.getServletResponse();
          response.setHeader("Content-disposition", "attachment; filename=" + id+ ".xls" ); //不是内嵌显示(inline),而是作为附件下载
          response.setContentLength(baos.size());
          ServletOutputStream sos=response.getOutputStream();
          baos.writeTo(sos);
          baos.close();
          sos.flush();
        } catch (IOException ex) {      
          logger.debug(ex);
        }   
      }
    <h:commandLink actionListener="#{productBean.downloadAction}" styleClass="highLightLink">
       <h:outputText value="download"/>
       <f:param name="productId" value="#{productBean.id}"/>
    </h:commandLink>出处http://blog.csdn.net/gohands/archive/2008/02/15/2096713.aspx
      

  2.   

    1楼给出的函数中第二个参数 HttpServletResponse 怎么用?
      

  3.   

    请问,你说的reponse.reset()非常重要;我想请问我的downFile()就没加那句,其他都跟你一样,结果点击down,进行相关操作后,再点jsp业务表单页面的保存时,会再次弹出下载提示框,请问是因为没加那句的缘故吗