java下载代码

来源:互联网 发布:js数字递增特效代码 编辑:程序博客网 时间:2024/06/08 07:12

 /*
  * 下载

  * param:filepath文件绝对路径
  */
 public void downLoad(HttpServletRequest request,HttpServletResponse response) throws IOException{
     String   file = request.getParameter("filepath");
     int in = file.lastIndexOf("/");
     String   fileName = file.substring(in+1, file.length());
  BufferedInputStream     bis = null;
  BufferedOutputStream    bos = null;
     try {
      response.setContentType("application/octet-stream"); 
      response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));   
   bis=new  BufferedInputStream(new FileInputStream(file));
   bos=new  BufferedOutputStream(response.getOutputStream());
   byte[]  by=new byte[2048];
   int     bytesRead;
   while(-1!=(bytesRead=bis.read(by,0,by.length))){
    bos.write(by, 0, bytesRead);
   }
   bis.close();
   bos.flush(); 
   bos.close();
  } catch (IOException e) {
   e.printStackTrace();
  }finally {
   if(bis!=null){
    bis.close(); 
   }
   if(bos!=null){
    bos.close();
   }   
     }
    }

0 0