如何使用 blob 在新选项卡中显示 pdf

Jet*_*mes 15 typescript angular

我在 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);
            });
        }
Run Code Online (Sandbox Code Playgroud)

这是我的服务

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;
            });
Run Code Online (Sandbox Code Playgroud)

就像代码中注释的那样,当我尝试在新选项卡中打开时,不起作用,仅当我在当前选项卡中打开时才有效

如何在新选项卡中打开此 blob pdf 文件?

小智 16

我可以让它像这样工作:

var fileURL = window.URL.createObjectURL(data);
let tab = window.open();
tab.location.href = fileURL;
Run Code Online (Sandbox Code Playgroud)

  • 更简单:`window.open(fileURL);` (9认同)

Amo*_*hor 10

要在新选项卡中打开文件,您需要在 Typescript 中创建锚元素,并在此元素的 href 属性中添加文件 url。

在我的示例中,服务响应与data._body文件 blob 相同,您可以将其安排为服务的输出响应。

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 
   }
);
Run Code Online (Sandbox Code Playgroud)

  • 我可以让它像这样工作`var fileURL = window.URL.createObjectURL(data); 让 tab = window.open(); tab.location.href = fileURL;` (4认同)
  • 有一个疑问,属性 `{ oneTimeOnly: true }` 是什么? (2认同)