如何使用blob

时间:2018-03-16 13:13:14

标签: angular typescript

我在TypeScript / Angular中有这个方法,它生成我的文件

 imprimir() {

            this.service.emitirAdvertencia({ parametros: [{ name: 'CODIGO', value: 880 }] })
            .subscribe((response) => {
                console.log(response);             
                var fileURL = window.URL.createObjectURL(response);                        

                //this not display my pdf document in a new tab.
                window.open(fileURL, '_blank');

                //this display my document pdf, but in current tab
                window.location.href = fileURL; 
            }, error => {
                console.log(error);
            });
        }

这是我的服务

emitirAdvertencia(parametros: Object): any {
        parametros['dbenv'] = ApplicationContext.getInstance().getDbenv();
        parametros['usuario'] = ApplicationContext.getInstance().getUser().codigoUsuario;
        parametros['nome_relatorio'] = 'RelAdvertenciaDB';
        var httpOptions = {

            headers: new HttpHeaders({
                'Authorization': this.localStorage.get('token'),
            }),
            responseType: 'blob' as 'blob',
        };
        return this.http.get(ApplicationContext.URL + '/adiantamento/gerar-relatorio/', httpOptions)
            .map((res) => {
                var report = new Blob([res], { type: 'application/pdf' });
                return report;
            });

就像代码中的注释一样,当我尝试在新标签页中打开时,不起作用,只有在我在当前标签页中打开时才有效

如何在新标签页中打开此blob pdf文件?

2 个答案:

答案 0 :(得分:2)

  

要在新标签中打开文件,您需要在其中创建锚元素   打字稿并在此元素的href属性中添加文件URL。

在我的示例中,对于文件blob,服务响应为data._body,您可以将其作为服务的输出响应进行排列。

var newTab = true;
var inputData = { parametros: [{ name: 'CODIGO', value: 880 }] };

    this.service.emitirAdvertencia(inputData).subscribe(
                    (data: any) => {
                        var contentType = data.headers._headers.get('content-type')[0];
                        var blob = new Blob([data._body], { type: contentType });
                        var url = window.URL.createObjectURL(blob, { oneTimeOnly: true });

                        //window.open(url, '_blank', '');
                        var anchor = document.createElement('a');
                        anchor.href = url;
                        if (newTab)
                            anchor.target = '_blank';

                        anchor.click();
                    },
                    error => {
                        //TODO
                    },
                    () => { 
                        //TODO 
                    });

答案 1 :(得分:1)

我可以让它像这样工作:

var fileURL = window.URL.createObjectURL(data);
let tab = window.open();
tab.location.href = fileURL;