如何从IHttpActionResult数据在Angular中创建Blob对象(.PDF)?

时间:2019-07-26 09:29:53

标签: angular asp.net-web-api blob

我正在使用Blob从API(ASP.NET webAPI 2)查看PDF文件,并且都可以与Angular 5正常工作。

但是最近我们从Angular 5升级到了版本7,在查看PDF文件时开始出现错误。

请检查所附错误的屏幕截图

enter image description here

下面是我们的实现

Controller.cs

[HttpGet, Route("download")]
public IHttpActionResult DownloadReport(int ID) {
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var model = _report.GetPdfByte(ID);
    var stream = new MemoryStream(model.PDF) {
        Position = 0
    };
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentLength = model.PDF.Length;
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = model.Name };
    result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
    result.Content.Headers.ContentLength = stream.Length;
    return Ok(result);

}

service.ts

GetFile(url: string) {
    return this.http.get(this.hostName + url 
         ,{responseType: "blob"}
    );
}

component.ts

getReport(id:number) {
    this._db.GetFile('api/reports/download?id='+id).subscribe(d=>this.downloadReport(d));
}

//Blob-binary large object that stores a binary data..
// URl- it will generate custom url to read the Pdf file
downloadReport(data: any) {
    let blob = new Blob([data], {type: 'application/pdf'});
    let url= window.URL.createObjectURL(blob);
    window.open(url);
}

请帮助我解决或调试错误。

预先感谢

0 个答案:

没有答案