Downloading and saving files from server using AngularJS

本秂侑毒 提交于 2019-12-03 14:19:03

I'd guess that you're not getting a byte array back from your $http.get call. Try adding:

vm.download = function (filename) {
var config = {headers: {
        'Accept': "image/jpeg"
    }
};
$http.get('api/files/download/' + filename, config).then(function (response)             { 
       var myBuffer= new Uint8Array( response.data );

    var data = new Blob([myBuffer], {type: 'image/jpeg;charset=UTF-8'});
    FileSaver.saveAs(data, filename);
        })
}

I have a special download service in angular that works very well and simple:

(function () {
    angular.module('common')
        .factory('downloadService', ['$http', '$window', 'contentDispositionParser',
            function ($http, $window, contentDispositionParser) {
                return {
                    downloadFile: downloadFile
                };

                function downloadFile(url, request)
                {
                    $http({
                        url: url, 
                        method: 'GET',
                        params: request,
                        responseType: 'blob'
                    })
                    .success(function (data, status, headers, config){
                        var disposition = headers('Content-Disposition');
                        var filename = contentDispositionParser.getFileName(disposition);
                        $window.saveAs(data, filename); // This is from FileSaver.js
                    });
                }

            }]);
})();

Filesaver.js is from here. ContentDispositionParser you can use anything or write yourself, it's only used for getting the proper filename, since it is apparently not an easy task, but not directly connected to saving the file itself (you might add the name in js e.g.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!