当前位置: 移动技术网 > IT编程>开发语言>JavaScript > http请求post,文件导出兼容IE10+

http请求post,文件导出兼容IE10+

2019年08月01日  | 移动技术网IT编程  | 我要评论

1.post的方法里要加responsetype: 'blob'参数,不然下载的excel会乱码

2.使用{type: "application/vnd.ms-excel"}的写法,可以保存为xls格式的excel文件(兼容老版本)。而使用“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”则会保存为xlsx

3.返回结果为下载excel文档链接,使用window.open(result)即可

4.使用增加节点调用click方法,而不使用window.open(objecturl)方法,是防止被浏览器当插件屏蔽弹出连接

5.给文件设定名字,直接在a标签的download属性中设置即可

1、方法1

axios.post('/getexcel',{},{responsetype:'blob'}).then((res:any)=>{
     let reader = new filereader()
     reader.readasdataurl(res);
     reader.onload = (e:any)=>{
          var a = document.createelement('a');
          document.body.appendchild(a);
          a.style.display = 'none';
          a.href =  e.target.result;
          a.download = 'name.xlsx';
          a.click();
          a.remove();
     }
})

2、方法2

      var download = function (file_name:string, content:any) {
                var csvdata = new blob([content], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
                // for ie
                if (window.navigator && window.navigator.mssaveoropenblob) {
                    window.navigator.mssaveoropenblob(csvdata, file_name);
                }
                // for non-ie (chrome, firefox etc.)
                else {
                    var a = document.createelement('a');
                    document.body.appendchild(a);
                    a.style.display = 'none';
                    var url = window.url.createobjecturl(csvdata);
                    a.href =  url;
                    a.download = file_name;
                    a.click();
                    a.remove();
                    window.url.revokeobjecturl(url);
                }
            };
            this.$axios.post('/getexcel',{},{responsetype:'blob'}).then((res:any)=>{
                download('name',res);
            })

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网