Spring MVC 文件下载

2018-04-14 18:33:33
770次阅读
0个评论


/**
	 * 下载
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params="method=download", method=RequestMethod.GET)
	public String download(ModelMap model,String dirName,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
			//文件路径
			String path = "c://1.rar";
			
			String fileName = "rar";//获取文件名,含后缀
			
			File file = new File(path);
      response.reset();
      response.setContentType("application/octet-stream; charset=UTF-8");
      fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器 
      response.addHeader("Content-Disposition","attachment;filename="+fileName); 
      response.setContentLength((int) file.length());

      byte[] buffer = new byte[4096];
      BufferedOutputStream output = null;
      BufferedInputStream input = null;

      // 写缓冲区:
      try {
          output = new BufferedOutputStream(response.getOutputStream());
          input = new BufferedInputStream(new FileInputStream(file));

          int n = (-1);
          while ((n = input.read(buffer, 0, 4096)) > -1) {
              output.write(buffer, 0, n);
          }
          response.flushBuffer();
      }
      catch (Exception e) {
      } // maybe user cancelled download
      finally {
          if (input != null) input.close();
          if (output != null) output.close();
      }
	        
			
			
	
		return null;
	}


收藏00

登录 后评论。没有帐号? 注册 一个。