Download a file from server using angularjs

前端 未结 1 1180
滥情空心
滥情空心 2021-01-14 21:23

I searching for a way to enable the user select a file exists on the server and download it using angularjs , I found this code which didn\'t work , so does anyone have a w

相关标签:
1条回答
  • 2021-01-14 22:03

    I do it this way:

    <a href="download.txt" data-file-download="true">Download</a>
    

    and use the directive:

    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 });
                    }
                }]
            }
        }]);
    

    this uses the jQuery fileDownload function to download the file. (note: there is also the dialogs class in effect)

    0 讨论(0)
提交回复
热议问题