文件下载一般比较麻烦,这里使用angularjs的指令进行封装,可以方便调用。
此指令并没有做断点续传,因为断点续传需要将保存断点传输字节流到redis里面。
1. drDownFileLink指令
directives.directive('drDownFileLink', ['$cordovaFileTransfer', '$timeout','$ionicLoading','IonicNoticeService'
, function ($cordovaFileTransfer, $timeout,$ionicLoading,IonicNoticeService) {
return {
restrict: 'AE',
scope: {fileName: '=', url: '=', prefix:'=', initText:'@'},
replace: true,
template: '<a ng-click="download()">{{initText}}</a>',
link: function (scope, element, attrs) {
var lnk = element.find('a');
for (key in attrs.$attr) {
lnk.attr(key, attrs.$attr[key]);
}
scope.download = function(){
console.log(scope.fileName);
console.log(scope.url);
console.log(scope.prefix);
var _onDeviceReady = function () {
var targetPath = cordova.file.externalRootDirectory + scope.fileName;
var trustHosts = true;
var options = {};
var url = scope.prefix + scope.url;
$ionicLoading.show({template: "已经下载:0%"});
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function (result) {
IonicNoticeService.show('下载完成,文件保存在:'+targetPath,5000);
}, function (err) {
IonicNoticeService.show(err);
}, function (progress) {
// 显示下载进度
$timeout(function () {
var downloadProgress = (progress.loaded / progress.total) * 100;
console.log(url);
console.log(downloadProgress);
$ionicLoading.show({
template: "已经下载:" + Math.floor(downloadProgress) + "%"
});
if (downloadProgress > 99) {
$ionicLoading.hide();
}
})
});
}
document.addEventListener('deviceready', _onDeviceReady, false);
}
}
}
}]);
2 html端调用
<dr-down-file-link init-text="下载" file-name="designchart.absDesignChart.constructDrawName"
url="designchart.absDesignChart.constructDrawPath"
prefix="prefix"
class="button button-assertive button-full button-small" style="background: #ff6600" >
</dr-down-file-link>
3 controller
controller不需要做什么,只需要给name和url传值就可以