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

经测试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 "";
 }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值