从WebAPI发送的字节数组中获取Anguar 6打开pdf

时间:2018-10-19 08:53:45

标签: angular typescript google-chrome pdf httpclient

嗨,我在从WebAPI发送的字节数组中打开pdf时遇到问题。

我的服务:

getPdfDocument(): Observable<any> {
        return this.httpClient
            .get(this.configuration.serverUrl + this.configuration.getPdfDoc, {
                responseType: "arraybuffer" //tried with 'blob'
            });
}

我的组件

this.service.getPdfDocument()
        .subscribe(data => {
            var file = new Blob([data], { type: 'application/pdf' });   
            this.pdfContent = URL.createObjectURL(file);
            window.open(this.pdfContent);
        })

当我运行它时,我无法加载PDF文档...我仍然没有弹出窗口...

enter image description here

2 个答案:

答案 0 :(得分:1)

尝试这个:

服务:

getPdfDocument(): Observable<any> {
    let headers = new HttpHeaders({ 'Content-Type': 'application/JSON' });
    return this.httpClient
               .get(this.configuration.serverUrl + this.configuration.getPdfDoc,
                    { headers: headers, responseType: 'blob' as 'json', observe: 'response' as 'body' }
                });
        }

请求:

this.service.getPdfDocument()
        .subscribe(
                (data) => {
                    this.openFileForPrint(data);
                });

openFileForPrint(data: HttpResponse<any>) {
        let fileUrl = window.URL.createObjectURL(data);
        window.open(fileUrl, '_blank', 'location=yes,height=600,width=800,scrollbars=yes,status=yes');
    }

服务器端

[HttpGet]
public HttpResponseMessage getpdf(DateTime datum, int idlokacija)
{
    var r = _printService.getdata(datum, idlokacija);
    if (r == null)
    {
        return new HttpResponseMessage(HttpStatusCode.NotFound);
    }
    return SendPdfFile(r);
}

public static HttpResponseMessage SendPdfFile(string filePath, bool brisanje = true)
{
    var stream = new FileStream(filePath, FileMode.Open);
    HttpResponseMessage response = new FileHttpResponseMessage(filePath, brisanje)
    {
        StatusCode = HttpStatusCode.OK,
        Content = new StreamContent(stream)
    };
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    return response;
}

答案 1 :(得分:0)

尝试将responseType从arraybuffer更改为blob

您还可以使用以下技巧来设置文件名:

let a = document.createElement("a");
a.href = URL.createObjectURL(result);
a.download = "File_name_xxx";
a.click();

很高兴知道URL.createObjectURL在IE11上不起作用。您必须使用window.navigator.msSaveOrOpenBlob方法来支持IE11。这将需要其他条件,具体取决于用户浏览器。