ionic实现下载文件并打开功能(file-transfer和file-opener2插件
作为一款app,下载文件功能,和打开文件功能,在某些场景下还是十分有必要的。使用cordova-plugin-file-transfer和cordova-plugin-file-opener2这两个插件能够在ionic比较容易的实现这个功能。 1、安装: cordova plugin add cordova-plugin-file-transfer cordova plugin add cordova-plugin-file-opener2 2、代码实现 angular.module("app").controller("accessoryDetailCtrl",["$scope","$ionicLoading",function ($scope $ionicLoading) { "use strict"; $scope.downLoadFile = (downloadUrl) => { let fileTransfer = new FileTransfer(),uri = encodeURI(downloadUrl),// 文件的地址链接 fileUrl = cordova.file.dataDirectory + uri.substr(uri.lastIndexOf("/") + 1); // 文件的下载地址 fileTransfer.download(uri,fileUrl,entry => { entry.file(data => { cordova.plugins.fileOpener2.showOpenWithDialog(fileURL,data.type); // showOpenWithDialog使用手机上安装的程序打开下载的文件 }); console.log("download accessory successful. accessory information : " + JSON.stringify(entry)); },error => { console.error("download accessory fail. Because of : " + JSON.stringify(error)); }); fileTransfer.onprogress = function(progressEvent) { // 加载过程中的loading提示 const percentFinished = 99; let downloadProgress = Math.round((progressEvent.loaded / progressEvent.total) * $scope.percentage); $ionicLoading.show({ template: "正在下载" + downloadProgress + "%" }); downloadProgress > percentFinished && $ionicLoading.hide(); }; }; }]); 3、注意事项 在使用file-opener2时,需要传入mineType,这个我们可以在file-transfer时获取。 最后,在android7,android8上使用file-transfer插件有需要特殊的处理,详细可以查看一下github (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |