java 下載文件功能代碼例子

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();
    
 }firefox

相關文章
相關標籤/搜索