spring mvc 模板下載

来源:互联网 发布:js this指向问题 编辑:程序博客网 时间:2024/06/12 23:47

 @RequestMapping(value = "/download", method = RequestMethod.GET)
 public void download(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
  try {
   String tempPath = "/template/import.txt";
   String path = session.getServletContext().getRealPath("/");
   path = new String(path.getBytes("ISO-8859-1"), "UTF-8");
   path = path.replace("\\\\", "/");
   File file = new File(path + tempPath);
   if (!file.isFile() || !file.exists() || file.isDirectory()) {
    throw new RuntimeException("下載的文件路徑或文件不存在!");
   }
   response.setContentType("octets/stream");
   response.setContentLength((int) file.length());
   response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
   FileInputStream fis = new FileInputStream(file);
   BufferedInputStream buff = new BufferedInputStream(fis);
   byte b[] = new byte[1024];
   long k = 0;
   OutputStream out = response.getOutputStream();
   while (k < file.length()) {
    int j = buff.read(b, 0, 1024);
    k += j;
    out.write(b, 0, j);
   }
   out.flush();
   buff.close();
   out.close();
  } catch (Exception e) {
   logger.error(ExceptionUtils.getStackTrace(e));
   throw new RuntimeException(e);
  }
 }
0 0
原创粉丝点击