1. 程式人生 > >angularJS實現無刷新文件下載

angularJS實現無刷新文件下載

shee off window exc buffer 異步 open 接收 插件

 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實現無刷新文件下載