lundi 21 septembre 2015

call web api from javascript and return document

I have an Angular app where by I want to call my API and return a document for download. The document is stored in a MSSQL Db as an image datatype.

I've had success with the API using the following response message code

var ms = new MemoryStream(_document.Document);
        var response = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StreamContent(ms)};
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-word");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = string.Format("{0}.{1}", "testdocument, ".docx");
        return response;

This works well if calling myapi/Document in chrome, it will just download the document.

But I want to have a link in my angular app and trigger this download action.

So far I have managed to get it working by creating an "a" tag and forcing a click event using the following code

var a = window.document.createElement('a');

        a.href = SettingsService.getAPIURL() + "Document" + '/';
        a.download = "test";

        // Append anchor to body.
        document.body.appendChild(a);
        a.click();


        // Remove anchor from body
        document.body.removeChild(a);

The only problem with this is that I can't add any headers for my security tokens




Aucun commentaire:

Enregistrer un commentaire