我在寻找一种使用户能够选择服务器上存在的文件并使用angularjs下载文件的方法,我发现此代码无效,因此任何人都有一种可行的方法
var content = 'file content';
var blob = new Blob([content], { type: 'text/plain' });
$scope.download = function () {
$window.location = (window.URL || window.webkitURL).createObjectURL(blob);
}
<input type="button" value="download" download="content.txt" ng-click="download()"/>
我这样做:
<a href="download.txt" data-file-download="true">Download</a>
并使用指令:
angular.module('app')
.directive('fileDownload', [function () {
return {
restrict: 'A',
replace: true,
template: '<button class="btn btn-default" data-ng-click="download()"><span class="glyphicon glyphicon-download"></span></button>',
controller: ['$rootScope', '$scope', '$element', '$attrs', 'dialogs', '$timeout', function ($rootScope, $scope, $element, $attrs, dialogs, $timeout) {
$scope.progress = 0;
function prepare(url) {
dialogs.wait("Please wait", "Your download starts in a few seconds.", $scope.progress);
fakeProgress();
}
function success(url) {
$rootScope.$broadcast('dialogs.wait.complete');
}
function error(response, url) {
dialogs.error("Couldn't process your download!");
}
function fakeProgress() {
$timeout(function () {
if ($scope.progress < 95) {
$scope.progress += (96 - $scope.progress) / 2;
$rootScope.$broadcast('dialogs.wait.progress', { 'progress': $scope.progress });
fakeProgress();
}
}, 250);
}
$scope.download = function () {
$scope.progress = 0;
$.fileDownload($attrs.href, { prepareCallback: prepare, successCallback: success, failCallback: error });
}
}]
}
}]);
这使用jQuery fileDownload函数下载文件。(注意:还有一个有效的对话框类)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句