使用AngularJS从ASP.NET Web API方法下载文件

在我的Angular JS项目中,我有一个<a>锚标记,当单击它时会GET向返回文件的WebAPI方法发出HTTP 请求。


现在,我希望在请求成功后将文件下载到用户。我怎么做?


锚标记:


<a href="#" ng-click="getthefile()">Download img</a>

AngularJS:


$scope.getthefile = function () {        

    $http({

        method: 'GET',

        cache: false,

        url: $scope.appPath + 'CourseRegConfirm/getfile',            

        headers: {

            'Content-Type': 'application/json; charset=utf-8'

        }

    }).success(function (data, status) {

        console.log(data); // Displays text data if the file is a text file, binary if it's an image            

        // What should I write here to download the file I receive from the WebAPI method?

    }).error(function (data, status) {

        // ...

    });

}

我的WebAPI方法:


[Authorize]

[Route("getfile")]

public HttpResponseMessage GetTestFile()

{

    HttpResponseMessage result = null;

    var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.jpg");


    if (!File.Exists(localFilePath))

    {

        result = Request.CreateResponse(HttpStatusCode.Gone);

    }

    else

    {

        // Serve the file to the client

        result = Request.CreateResponse(HttpStatusCode.OK);

        result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));

        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");

        result.Content.Headers.ContentDisposition.FileName = "SampleImg";                

    }


    return result;

}


翻过高山走不出你
浏览 700回答 3
3回答
打开App,查看更多内容
随时随地看视频慕课网APP