Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

angular - Angular2 Displaying PDF

I have an angular2 project with an ASP.Net Web API. I have code to retrieve a file path from my database which goes to a document on my server. I then want to display this document in the browser in a new tab. Does anybody have any suggestions how to do this?

I am happy to retrieve the file in either Angular2 (Typescript) or in my API and stream it down.

This is my attempt of retrieving it in my API but i cannot work out how to receive it in Angular2 and display it properly:

public HttpResponseMessage GetSOP(string partnum, string description)
    {
        var sopPath = _uow.EpicorService.GetSOP(partnum, description).Path;
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new FileStream(sopPath, FileMode.Open);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
        return result;
    }

Any help would be greatly appreciated.

Many Thanks!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all, you need to set options for your http request - set responseType to ResponseContentType.Blob, use blob() to read response as blob and set its type to application/pdf:

downloadPDF(): any {
    return this._http.get(url, { responseType: ResponseContentType.Blob }).map(
    (res) => {
            return new Blob([res.blob()], { type: 'application/pdf' })
        }
}

Then, in order to get the file, you need to subscribe to it and you can create new ObjectURL and use window.open() to open PDF in new tab:

this.myService.downloadPDF().subscribe(
        (res) => {
        var fileURL = URL.createObjectURL(res);
        window.open(fileURL);
        }
    );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...