Angular 2使用webapi C#.net下载pdf

时间:2018-08-14 10:38:04

标签: angular

我有Angular 2和Web API应用程序,我正在尝试使用Web API下载pdf。下面是示例代码。当我单击下载按钮时,将获取请求发送到Web API,该API作为响应发送文件流,打字稿将此流转换为PDF。但是,当我打开此PDF时,它向我显示以下错误-“ Adob​​e Reader无法打开文件,因为它不是受支持的文件类型,或者因为文件已损坏”。

代码:WebAPI

[System.Web.Http.HttpGet]
public HttpResponseMessage GetReportPDF1(int ProjectID)
{
    string htmlContents = reportHTML.BuildHTMLDoc(ProjectID);
    byte[] temp = System.Text.Encoding.UTF8.GetBytes(htmlContents);
    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(temp)
    };

   result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

   result.Content.Headers.ContentDisposition =
             new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
             {
                 FileName = "Report.pdf"
             };

        return result;
    }

代码:component.ts

GenarateReportPDF() {           
    var ProjectID = localStorage.getItem('ProjectID');
    this._reportService.getReportPDF()
    .subscribe(
        response => { 
        var blob = new Blob([blob], {type: 'application/pdf'});
        var filename = 'file.pdf';
        filesaver. saveAs(blob, filename);
       },
        error => {
            console.error(`Error: ${error.message}`);
        }
    )
}

代码:Service.ts

getReportPDF(): Observable<any> {
    var ProjectID = localStorage.getItem('ProjectID');

    return this._http.get("http://localhost:52719/api/Report/GetReportPDF?ProjectID=" +ProjectID, 
                    { responseType:   ResponseContentType.Blob })
                    .map(res => res.blob())                      
}

0 个答案:

没有答案