作为一款 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-transfer 除了支持下载还有上传文件的功能, 下载的时候要注意的是下载的地址, ios 和 android 可以路径是不同的, 可以找出相同的路径, 或者分别处理, 这里使用的是 cordova.file.dataDirectory,ios 和 android 下载同一个路径
在使用 file-opener2 时, 需要传入 mineType, 这个我们可以在 file-transfer 时获取
file-opener2 除了我们使用的 showOpenWithDialog 方法, 还有 open 方法调用手机自带的打开功能, 可以用来实现 android 的版本更新, 下载新版本安装 (以后有时间在写, 网上的相关文档也很多)
另外还有 uninstall 和 appIsInstalled 功能, 项目中没有使用, 就不在研究了
最后, 在 android7,android8 上使用 file-transfer 插件有需要特殊的处理
来源: https://www.2cto.com/kf/201802/721137.html