AngularJs文件下载WebAPI

时间:2015-07-08 15:00:27

标签: angularjs asp.net-web-api

我需要使用Web API和angularJs从服务器下载文件。我在API控制器中使用下面的代码。当我通过浏览器点击API时,我可以下载该文件。我不知道怎么处理angualar

Web API

public HttpResponseMessage GetBrandByFilter(string filePath)
{
    filePath = "C:\\Temp\\DTA 517280.pdf"; //Just hard coded for testing 
    var fileinfo = new FileInfo(filePath);
    try
    {
        var excelData = File.ReadAllBytes(filePath);
        var result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new MemoryStream(excelData);

        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType =  
            new MediaTypeHeaderValue("application/octet-stream"); 

        result.Content.Headers.ContentDisposition =  
            new ContentDispositionHeaderValue("attachment")
            {
                FileName = fileinfo.Name
            };

        return result;
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
    }
}

角度控制器

$scope.downloadFile = function () {
    var result = downloadFile(service, "URL path"); 
    result.then(function (res, status, headers) {
        //****
        // looking for this code on success
        //****
    },
    function (err) {
        debugger;
        handleException($scope, err);
    })
};

1 个答案:

答案 0 :(得分:0)

如果需要,可以使用如下指令:

angular.module('app')
.directive('fileDownload', [function () {
    return {
        restrict: 'A',
        replace: true,
        scope: {},
        template: '<button class="btn btn-default" data-ng-click="download()"><span class="glyphicon glyphicon-download"></span></button>',
        controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
            $scope.progress = 0;

            function prepare(url) {
                console.log("Please wait, Your download starts in a few seconds.", $scope.progress);
                fakeProgress();
            }
            function success(url) {
                console.log("download complete");
            }
            function error(response, url) {
                console.log("Couldn't process your download!");
            }

            function fakeProgress() {
                $timeout(function () {
                    if ($scope.progress < 95) {
                        $scope.progress += (96 - $scope.progress) / 2;

                        fakeProgress();
                    }
                }, 250);
            }

            $scope.download = function () {
                $scope.progress = 0;
                $.fileDownload($attrs.href, { prepareCallback: prepare, successCallback: success, failCallback: error });
            }
        }]
    }
}]);

并像这样使用它:

<a href="/yourfiletodownload.pdf" file-download></a>