从WebAPI发送的字节数组中的Angular 6 open pdf

问题描述 投票:0回答:2

嗨,我在从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

angular typescript google-chrome pdf httpclient
2个回答
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;
}

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。这将需要其他条件,具体取决于用户浏览器。

© www.soinside.com 2019 - 2024. All rights reserved.