ionic實現下載文件並打開功能(file-transfer和file-opener2插件)

做爲一款app,下載文件功能,和打開文件功能,在某些場景下仍是十分有必要的。使用cordova-plugin-file-transfercordova-plugin-file-opener2這兩個插件可以在ionic比較容易的實現這個功能。android

一、安裝:ios

cordova plugin add cordova-plugin-file-transfer
cordova plugin add cordova-plugin-file-opener2

二、代碼實現git

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();
      };
    };
    
  }]);

三、注意事項
file-transfer除了支持下載還有上傳文件的功能,下載的時候要注意的是下載的地址,ios和android能夠路徑是不一樣的,能夠找出相同的路徑,或者分別處理,這裏使用的是cordova.file.dataDirectory,ios和android下載同一個路徑github

在使用file-opener2時,須要傳入mineType,這個咱們能夠在file-transfer時獲取。
file-opener2除了咱們使用的showOpenWithDialog方法,還有open方法調用手機自帶的打開功能,能夠用來實現android的版本更新,下載新版本安裝(之後有時間在寫,網上的相關文檔也不少)
另外還有uninstall和appIsInstalled功能,項目中沒有使用,就不在研究了。apache

最後,在android7,android8上使用file-transfer插件有須要特殊的處理,詳細能夠查看一下github
cordova-plugin-file-transferapp

相關文章
相關標籤/搜索