springboot+XMLHttpRequest文件下载

前端

html
 <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="download">下载</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>
JS
var url = "";
var xhr = new XMLHttpRequest();
xhr.open('GET', '/management/download/?'+ $.param(data), true);//get请求,请求地址,是否异步
xhr.responseType = "blob";  // 返回类型blob
xhr.onload = function () {// 请求完成处理函数
    if (this.status === 200) {
        var blob = this.response;// 获取返回值
        console.log(blob)
        var a = document.createElement('a');
        a.download = data.fileName;
        a.href=window.URL.createObjectURL(blob);
        a.click();
    }
};
xhr.send();
controller

这里controller的传值 是从前端动态接收下载路径和文件名

@RequestMapping("/download")
    public String fileDownLoad(@RequestParam Map<String,Object> options, HttpServletResponse response) throws UnsupportedEncodingException, MyException {
        String filename= options.get("fileName").toString();
        String filePath = "D:/" + options.get("directory").toString();
        File file = new File(filePath + "/" + filename);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download---" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else {
            throw new MyException("文件不存在");
        }
        return null;
    }