博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
angularJS实现无刷新文件下载
阅读量:5749 次
发布时间:2019-06-18

本文共 1706 字,大约阅读时间需要 5 分钟。

1 $scope.getExcel = function () {   2             $http.post("/production/statistics/export", {   3                 storeId: $scope.$parent.currStore.storeId,   4                 date: $scope.$parent.ledgerDate.getTime()   5             }, {responseType: "blob"}).success(function (data) {   6                 var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});   7                 var fileName = $scope.$parent.currStore.name + "_生产统计_" + $scope.$parent.ledgerDate.Format("yyyy-MM-dd");   8                 var a = document.createElement("a");   9                 document.body.appendChild(a);  10                 a.download = fileName;  11                 a.href = URL.createObjectURL(blob);  12                 a.click();  13             })  14         }

并且服务端返回的是二进制数据流.

客户端接收后转换为指定文件格式的blob,最后创建blob对象的URL 把它放在A标签的href上 就会自动下载了

或者

1 $http.post($rootScope.restful_api.last_output_excel,body_data,{responseType: 'arraybuffer'}).success(function(data){2                 var blob = new Blob([data], {type: "application/vnd.ms-excel"});3                 var objectUrl = URL.createObjectURL(blob);4                 var aForExcel = $("下载excel").attr("href",objectUrl);5                 $("body").append(aForExcel);6                 $(".forExcel").click();7                 aForExcel.remove();8             })

经验总结:

1.post的方法里要加responseType: 'arraybuffer'参数,不然下载的excel会乱码(这点一开始没注意到,费力好久)

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

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

另外也可以分为两步来做,一是异步请求判断下载是否存在,二是再次调用在后端通过response下载文件。

转载地址:http://jwezx.baihongyu.com/

你可能感兴趣的文章
Tomcat部署Web应用方法总结
查看>>
Python3 django2.0 字段加密 解密 AES
查看>>
CCNA实验之:网络地址转换(NAT)实验
查看>>
计算机网络原理笔记-停止等待协议
查看>>
/etc/resolv.conf文件详解
查看>>
【转】VC的MFC中重绘函数的使用总结(整理)
查看>>
JQuery日记_5.13 Sizzle选择器(六)选择器的效率
查看>>
oracle查看经常使用的系统信息
查看>>
Django_4_视图
查看>>
Linux的netstat命令使用
查看>>
lvm讲解,磁盘故障小案例
查看>>
大快网站:如何选择正确的hadoop版本
查看>>
经过这5大阶段,你离Java程序员就不远了!
查看>>
IntelliJ IDEA 连接数据库详细过程
查看>>
thymeleaf 学习笔记-基础篇
查看>>
PHP-X开发扩展
查看>>
android学习笔记——onSaveInstanceState的使用
查看>>
工作中如何做好技术积累
查看>>
怎么用sysLinux做U盘双PE+DOS??
查看>>
Spring Transactional
查看>>