前台页面
<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;
}
页面效果