java 下载文件功能代码例子

时间:2023-12-26 19:50:49

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

}