1.页面代码
<a class="layui-btn" href="${pageContext.request.contextPath}/bAndWListManage/downloadWhiteListTmp.do" onclick="downloadTemplate();">模板下载</a>
2.后台代码
@RequestMapping("downloadWhiteListTmp")
public ResponseEntity<byte[]> downloadWhiteListTmp(HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
String fileName="importVehicleWhitelist.xls";
ServletContext servletContext = request.getServletContext();
String realPath = servletContext.getRealPath("/bwlmm/templateFiles/"+fileName);
File file = new File(realPath);
InputStream in;
byte[] body=null;
ResponseEntity<byte[]> response =null;
try {
in = new FileInputStream(new File(realPath));
body=new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数
in.read(body);//读入到输入流里面
fileName=new String(fileName.getBytes("gbk"),"iso8859-1");//防止中文乱码
headers.add("Content-Disposition", "attachment;filename="+fileName);
HttpStatus statusCode = HttpStatus.OK;//设置响应吗
response =new ResponseEntity<byte[]>(body, headers, statusCode);
} catch (FileNotFoundException e) {
e.printStackTrace();
}//将该文件加入到输入流之中
catch (IOException e) {
e.printStackTrace();
}
return response;
}
3.说明
我的文件路径