首页 > Web开发 > 详细

angularJS实现无刷新文件下载

时间:2017-06-20 23:46:04      阅读:494      评论:0      收藏:0      [点我收藏+]
 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 = $("<a><span class=‘forExcel‘>下载excel</span></a>").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下载文件。

angularJS实现无刷新文件下载

原文:http://www.cnblogs.com/lcngu/p/7056875.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!