window.openurl仅使用原始文本打开新窗口,而不是下载

问题描述

当我使用以下方法时:

downloadFile(){
  const blob = this.b64toBlob(this.formGroup.value.attachment);
  const url = window.URL.createObjectURL(blob);
  window.open(url);
}

我希望它可以打开一个标签页并下载文件

但是它只是打开一个内部包含原始文本内容的新标签页。 This is the result I get

但是,如果我将页面内容复制/粘贴为URL,则效果很好,并且下载已按预期开始。

我应该怎么做才能直接开始下载。

PS:这是b64toBlob()方法

b64toBlob(b64Data: string,contentType = '',sliceSize = 512): Blob {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset,offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
}

  return new Blob(byteArrays,{type: contentType});
}

解决方法

代替使用URL,在其中创建一个href,您可以使用相应的click函数。请更改您的以下功能,如下所示,希望您可以下载该文件。

downloadFile(){
            var a: any = document.createElement("a");
            a.setAttribute('style','display:none;');
            const blob = this.b64toBlob(this.formGroup.value.attachment);
            const url = window.URL.createObjectURL(blob);
            a.href = url;
            a.click();
        }

有时,此点击在IE中无法正常工作。在这种情况下,您可以使用msSaveBlob函数。整个功能可以像这样更改:

downloadFile() {
        var a: any = document.createElement("a");
        a.setAttribute('style','display:none;');
        document.body.appendChild(a);
        const blob = this.b64toBlob(this.formGroup.value.attachment);
        const url = window.URL.createObjectURL(blob);
        a.href = url;

        var isIE = /*@cc_on!@*/false || !!(<any>document).documentMode;

        if (isIE) {
            var retVal = navigator.msSaveBlob(blob,"test"+ '.txt');
        }
        else {
            a.download = "test" + '.txt';
        }
        a.click();
    }
,

所以经过几个小时的研究...

我设法使它按预期工作。

如果有人遇到同样的问题,请发布答案:

downloadFile() {
 const blob = this.b64toBlob(this.formGroup.value.attachment);
 blob.text().then(result => { // waiting for blob content to be available... 
   const a: any = document.createElement('a');
   a.download = 'test.pdf'; // or whatever your file name is
   a.href = result;
   a.click();
 });
}

a.download ='test.pdf'行在chrome上似乎是必需的,但在Firefox上没有它就可以正常工作。

希望这对其他人有帮助。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...