angularJS实现无刷新文件下载
2023-09-27 14:27:16 时间
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下载文件。
相关文章
- PHP实现大文件下载
- 028_如何外网下载大文件
- Android Webview实现文件下载功能
- Folx Pro5下载器堪比IDM的下载工具 支持下载磁力链接和种子文件
- Spring Websocket实现文本、图片、声音、文件下载及推送、接收及显示(集群模式)
- 学习springboot days3-postman实现上传以及下载文件
- HDFS 文件的上传与下载
- js文件下载blob
- 任意文件下载包含https的图片
- SSH上传/下载本地文件到linux服务器
- Spring Boot入门(11)实现文件下载功能
- python实现文件下载的方法总结
- 通过HttpURLConnection 上传和下载文件(二)
- WCF HTTP 错误 404.3 - Not Found(因为扩展配置问题而无法提供您请求的页面。假设该页面是脚本,请加入处理程序。假设应下载文件,请加入 MIME 映射。)
- Spring MVC 实现文件的上传和下载
- vue 实现文件上传和文件下载
- Java实现批量下载多文件(夹)压缩包(zip)续
- 使用Servlet实现下载文件的功能
- spring boot 实现文件下载
- dotnet 通过 HttpClient 下载文件同时报告进度的方法