jsf浏览器文件下载的实现及问题!

来源:互联网 发布:金蝶智慧记mac版 编辑:程序博客网 时间:2024/06/05 06:47

经测试IE,chrome,欧鹏等浏览器都可以正常实现文件下载,但是360浏览器下载文件时,当文件太小估计小于6kb时无法正常下载,但文件比较大时就没问题了。

下载代码:

 

jsf:<h:commandButton value="下载" action="#{userinfoBean.download}"></h:commandButton>

javaBean:

public String download() {
  
  FacesContext ctx = FacesContext.getCurrentInstance();
  HttpServletRequest request=(HttpServletRequest)ctx.getExternalContext().getRequest();
  
  String filepath="D://tt.txt";
//  String filepath=conn.getfilepath(Integer.parseInt(request.getParameter("fileid")));//"C://Program Files//Apache Software Foundation//Tomcat 5.0//webapps//FileUploadDown//upload//007.txt";
  if(!new File(filepath).exists()){
   System.out.println("文件不存在...........");
   return "";
  }
  try {
   String contentType = "application/octet-stream;charset=iso8859-1";
   HttpServletResponse response = (HttpServletResponse) ctx
     .getExternalContext().getResponse();
   response.setContentType(contentType);
   StringBuffer contentDisposition = new StringBuffer();
   contentDisposition.append("attachment;");
   contentDisposition.append("filename=\"");
   contentDisposition.append(new File(filepath).getName());
   contentDisposition.append("\"");
   //logger.debug(System.getProperty("file.encoding"));
   response.setHeader("Content-Disposition", new String( contentDisposition.toString().getBytes(System.getProperty("file.encoding")), "iso8859-1"));
   //logger.debug(contentDisposition.toString());
   OutputStream out = response.getOutputStream();

   byte[] bytes = new byte[1024];
   InputStream is = new FileInputStream(filepath);
   int b = 0;
   while ((b = is.read(bytes, 0, 1024)) > 0) {
    out.write(bytes, 0, b);
   }
   is.close();
   out.flush();
   ctx.responseComplete();
   
  } catch (Exception e) {
   e.printStackTrace();
  }
  return "";
 }