使用angularjs从服务器下载文件

时间:2014-11-20 08:01:25

标签: angularjs download

我正在寻找一种方法来让用户选择服务器上存在的文件并使用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()"/>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我是这样做的:

<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函数来下载文件。 (注意:还有对话框类有效)