Download a file from server using angularjs

前端 未结 1 1179
滥情空心
滥情空心 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:

    Download
    

    and use the directive:

    angular.module('app')
        .directive('fileDownload', [function () {
            return {
                restrict: 'A',
                replace: true,
                template: '',
                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)
提交回复
热议问题