1. 程式人生 > >springMVC下載功能

springMVC下載功能

調用 head 下載 ade java tac 讀取 防止 servle

前臺頁面

<a href="download">下載</a>

後臺代碼

/**
	 * 文件下載
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/download")
	public ResponseEntity<byte[]>   download(HttpServletRequest request) throws IOException{
	      String fileName="book.xml";
	      //得到文件所在位置
	      String realPath ="c://book.xml";
	      //將該文件加入到輸入流之中
	      InputStream in=new FileInputStream(new File(realPath));
	      byte[] body=null;
	      // 返回下一次對此輸入流調用的方法可以不受阻塞地從此輸入流讀取(或跳過)的估計剩余字節數
	      body=new byte[in.available()];
	      //讀入到輸入流裏面
	      in.read(body);
	      //防止中文亂碼
	      fileName=new String(fileName.getBytes("gbk"),"iso8859-1");
	      //設置響應頭
	      HttpHeaders headers=new HttpHeaders();
	      headers.add("Content-Disposition", "attachment;filename="+fileName);
	      //設置響應嗎
	      HttpStatus statusCode = HttpStatus.OK;
	      ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode);
	      return response;
	}
	

  

頁面效果

技術分享圖片

springMVC下載功能