Java文件下载代码

public static void DownLoadFile(String filePath, String fileName,
                  HttpServletResponse response) throws Exception {
            System.out.println("filepath:" + filePath);
            File file = new File(filePath);
            if (!file.exists()) {
                  System.out.println("文件不存在");
            } else {
                  FileInputStream fis = new FileInputStream(file);
                  BufferedInputStream bis = new BufferedInputStream(fis);
 
                  OutputStream os = response.getOutputStream();
                  BufferedOutputStream bos = new BufferedOutputStream(os);
 
                  fileName = URLEncoder.encode(fileName, "UTF-8");
                  fileName = new String(fileName.getBytes("UTF-8"), "GBK");
 
                  response.reset();
                  response.setContentType("UTF-8");
                  response.setContentType("Application/x-msdownload");
                  response.setHeader("Content-Disposition", "attachment;filename="
                              + fileName);
                  response.setHeader("Content-Length", String
                              .valueOf(bis.available()));
 
                  int bytesRead = 0;
                  byte[] buffer = new byte[1024];
                  while ((bytesRead = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, bytesRead);
                  }
                  bos.flush();
                  bos.close();
                  bis.close();
 
                  os.close();
                  fis.close();
            }
      }

posted on 2013-11-08 14:40  全袁君  阅读(325)  评论(0编辑  收藏  举报

导航