Laden Sie die Datei von einer ASP.NET-Web-API-Methode mit AngularJS herunter

In meinem Angular JS-Projekt, ich habe eine <a> Anker-Tags, die, wenn Sie geklickt haben, wird eine HTTP - GET Anfrage zu einem WebAPI-Methode gibt eine Datei an.

Nun möchte ich die Datei heruntergeladen werden, um den Benutzer, sobald die Anforderung erfolgreich. Wie mache ich das?

Anker-tag:

<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) {
        //...
    });
}

Meinen WebAPI Methode:

[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;
}

InformationsquelleAutor der Frage Amar Duplantier | 2014-06-06

Schreibe einen Kommentar