vue 二进制流文件导出、下载,兼容IE

this.$ajax({
                method: 'GET',
                url: '你的url',
                headers: {
                    'Authorization': tokenUtil.getToken(), // 我的token
                    'Content-Type': "application/json;charset=utf-8"
                },
                responseType: 'blob',  // 很重要
                params: params // 请求入参
            })
            .then(res =>{
                // console.log(res)
                let headersName = '';
                if(res.headers['content-disposition']) {
                    headersName = res.headers['content-disposition'].split('=')[1];
                }
                 else {
                    headersName = '文件名称';
                }
                let fileName = decodeURI(headersName);
                let blob = new Blob([res.data], {type: 'application/vnd.ms-excel'});  // 注意你的文件类型,我的是excel,需要什么类型文件,对应修改即可
                // IE兼容
                if (window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveOrOpenBlob(blob, fileName);
            } else {
                    var a = document.createElement('a');
                    a.download = fileName;
                    a.href = URL.createObjectURL(blob);
                    a.setAttribute("id", "export");
                    document.getElementById("platform").append(a); // 修复firefox中无法触发click, platform 为我本页div 的id, 此处可直接用document.body
                    a.click();
                    document.getElementById("export").remove();
                }
                this.loading = false;
            })
            .catch(err =>{
                this.loading = false;
            })
posted @ 2020-07-28 16:15  傲气中华  阅读(1733)  评论(0编辑  收藏  举报