前端js
function downloadFile(){ var url=contextPath + 'downloadFile/downModel?fileName='模板的名称'.xls'; window.open(url);//跳转后台的路径 }
这就是后台完整的下载模板的代码
@ApiOperation("下载模板")
@RequestMapping(value = "/downModel",method = RequestMethod.GET,produces="application/json")
public Result<Object> downModel(HttpServletResponse response, HttpServletRequest request) {
Result<Object> result=Result.ok();
String fileName = request.getParameter("fileName");
ServletOutputStream out;
response.setContentType("multipart/form-data");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
try{
String filePath = getClass().getResource("/static/template/" + fileName).getPath();//文件在项目中的存放路径
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE浏览器的处理:
fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
}
filePath = URLDecoder.decode(filePath, "UTF-8");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
FileInputStream inputStream = new FileInputStream(filePath);
out = response.getOutputStream();
int b = 0;
byte[] buffer = new byte[1024];
while ((b = inputStream.read(buffer)) != -1) {
// 4.写到输出流(out)中
out.write(buffer, 0, b);
}
inputStream.close();
if (out != null) {
out.flush();
out.close();
}
}catch (Exception e){
log.error(ExceptionUtils.getMessage(e));
log.error(ExceptionUtils.getStackTrace(e));
return Result.error(e.getMessage());
}
return null;
}