ajax 请求 后台返回的文件流

download(url) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);    // 也可以使用POST方式,根据接口
            xhr.responseType = "blob";  // 返回类型blob
            // 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
            xhr.onload = function () {
                // 请求完成
                if (this.status === 200) {
                    // 返回200
                    var blob = this.response;
                    var reader = new FileReader();
                    reader.readAsDataURL(blob);  // 转换为base64,可以直接放入a表情href
                    reader.onload = function (e) {
                        // 转换完成,创建一个a标签用于下载
                        var a = document.createElement('a');
                        a.download = 'data.xlsx';
                        a.href = e.target.result;
                        // $("body").append(a);  // 修复firefox中无法触发click
                        a.click();
                        // $(a).remove();
                    }
                }
            };
            // 发送ajax请求
            xhr.send()
        }

前置知识

a标签的属性

http://www.w3school.com.cn/tags/tag_a.asp

js 的 blob对象

http://blog.csdn.net/oscar999/article/details/36373183

dataUrl

http://www.webhek.com/post/data-url.html

Blob 对象的基本应用

http://www.cnblogs.com/wangfajing/p/7202139.html?utm_source=itdadao&utm_medium=referral

fileReader

http://blog.csdn.net/yaoyuan_difang/article/details/38582697

Ajax请求二进制流进行处理(ajax异步下载文件)的简单方法

http://www.jb51.net/article/122797.htm

XMLHttpRequest Level 2 使用指南

http://www.ruanyifeng.com/blog/2012/09/xmlhttprequest_level_2.html

posted @ 2017-10-20 14:08  浪迹灬天涯  阅读(2972)  评论(0编辑  收藏  举报