码迷,mamicode.com
首页 > 编程语言 > 详细

java 下载文件功能代码例子

时间:2015-02-10 18:26:23      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

public static void down(HttpServletRequest request,
   HttpServletResponse response) throws Exception {
  
  
  String name="aaa.*";//文件名
  String uploadPath = UploadFileHelper.getRepositoryPath()+"//";//文件来源
    
   String filePath = name;
  String fileName = name;
  
  
  if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0){
   fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
  }else {
       if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
        fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
       }
  }  
  response.setContentType("text/plain");
  response.setHeader("Location",fileName);
  response.reset();
  response.setHeader("Cache-Control", "max-age=0" );
  response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
 BufferedInputStream bis = null;
  BufferedOutputStream bos = null;
  OutputStream fos = null;
  InputStream fis = null;
  filePath = uploadPath + filePath;
  fis = new FileInputStream(filePath);
     bis = new BufferedInputStream(fis);
     fos = response.getOutputStream();
     bos = new BufferedOutputStream(fos);

int bytesRead = 0;
     byte[] buffer = new byte[5 * 1024];
     while ((bytesRead = bis.read(buffer)) != -1) {
         bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
     }
     bos.close();
     bis.close();
     fos.close();
     fis.close();
    
 }

java 下载文件功能代码例子

标签:

原文地址:http://www.cnblogs.com/sand-tiny/p/4284450.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!