ionic achieve download the file and open function (file-transfer and file-opener2 plug)

As an app, download files function, and open files function, in some scenarios still very necessary. Use cordova-plugin-file-transfer and cordova-plugin-file-opener2 two plug-ins can be relatively easy to implement this feature in ionic.

1, the installation:

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

2, code implementation

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 Notes
file-transfer support function in addition to download as well as upload files, download time to pay attention is to download the address, ios and android paths may be different, you can find the same path, or treated separately, use here is cordova.file.dataDirectory, ios and android download the same path

When using the file-opener2, need to pass mineType, we can get this in the file-transfer.
In addition to file-opener2 showOpenWithDialog method we use, as well as the open method calls the phone comes with opening function can be used to achieve the android version of the update, download the new version is installed (after a time in writing, online documentation for a lot)
Also there uninstall and appIsInstalled function, the project is not used, not in the study.

Finally, the use of file-transfer plug-in on android7, android8 need special handling, you can look at in detail GitHub
cordova-plugin-file-transfer

Guess you like

Origin www.cnblogs.com/jlfw/p/11972905.html