SpringBoot利用Ajax在页面按钮下载

介绍

关于下载的代码量其实不多,给链接加上a标签,达到点击下载的功能

GIIF展示

在这里插入图片描述

后台代码

@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>
posted @ 2020-03-30 09:23  YafengLiang  阅读(44)  评论(0)    收藏  举报  来源