介绍
关于下载的代码量其实不多,给链接加上a标签,达到点击下载的功能
GIIF展示
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200330091803675.gif)
后台代码
@RequestMapping(value = "export")
@ResponseBody
public ResponseEntity exportFile (HttpServletResponse response,HttpSession session, HttpServletRequest request) throws UnsupportedEncodingException {
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=123.xml");
String str = "123";
byte[] bytes = str.getBytes("UTF-8");
return new ResponseEntity(bytes,HttpStatus.OK);
}
前台代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body style="margin: 100px 100px 100px">
<a href="http://localhost:8080/export">下载</a>
<br><br>
<button type="button" id="down">download</button>
</body>
<script src="jquery.min.js" th:src="@{/jquery.min.js}" ></script>
<script>
$("#down").on("click",function () {
$.ajax({
url:"/export",
type:"get",
success:function (date) {
const link = document.createElement('a');
link.href = 'export';
link.click()
},
error:function () {
alert("error")
}
})
})
</script>
</html>