【问题标题】:Download PDF not working with Firefox using Angular 2 and Node.js使用 Angular 2 和 Node.js 下载 PDF 不适用于 Firefox
【发布时间】:2019-04-05 12:34:05
【问题描述】:

我正在从节点 JavaScript 后端获取 base64 字符串。但它不像 Chrome 那样工作。

我在网络上找不到任何解决方案。在 API 调用中获得 200 状态,但它没有在 Firefox 中下载文件,而相同的代码在 Chrome 中运行良好。

这是我的代码::

static downloadFile(fileName: string, fileMimeType: string, uri: string) {
    const dataURI = uri;
    const blob = this.dataURIToBlob(dataURI);
    const url = URL.createObjectURL(blob);
    const blobAnchor = document.createElement('a');
    const dataURIAnchor = document.createElement('a');
    blobAnchor.download = dataURIAnchor.download = fileName;
    blobAnchor.href = url;
    dataURIAnchor.href = dataURI;

    blobAnchor.onclick = function () {
        requestAnimationFrame(function () {
            URL.revokeObjectURL(url);
        });
    };

    blobAnchor.click();
}

static dataURIToBlob(dataURI) {

    const binStr = atob(dataURI.split(',')[1]),
        len = binStr.length,
        arr = new Uint8Array(len),
        mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    for (let i = 0; i < len; i++) {
        arr[i] = binStr.charCodeAt(i);
    }

    return new Blob([arr], {
        type: mimeString
    });

}

我正在从 Node.js 获取所有数据并在 Chrome 上正常工作。所以我找不到任何问题,为什么它不能与 Firefox 一起使用。

【问题讨论】:

  • 当你说它不起作用时,你能具体点吗?怎么了?有没有错误?
  • 不,错误。发布请求已成功完成并收到了 pdf 的 base64,但没有在 firefox 中下载。

标签: javascript node.js angular pdf


【解决方案1】:

在 Firefox 中,您必须将 a 附加到 DOM 中,然后执行单击。

使用document.body.appendChild(blobAnchor); 追加到 DOM。

添加了blobAnchor.className = 'hidden';,使其不可见。

并在几秒钟后使用 setTimeout(() =&gt; blobAnchor.remove(), 300); 从 DOM 中删除。

static downloadFile(fileName: string, fileMimeType: string, uri: string) {
    const dataURI = uri;
    const blob = this.dataURIToBlob(dataURI);
    const url = URL.createObjectURL(blob);
    const blobAnchor = document.createElement('a');
    const dataURIAnchor = document.createElement('a');
    blobAnchor.download = dataURIAnchor.download = fileName;
    blobAnchor.className = 'hidden';
    blobAnchor.href = url;
    dataURIAnchor.href = dataURI;
    document.body.appendChild(blobAnchor);

    blobAnchor.onclick = function () {
        requestAnimationFrame(function () {
            URL.revokeObjectURL(url);
            setTimeout(() => blobAnchor.remove(), 300);
        });
    };

    blobAnchor.click();
}

static dataURIToBlob(dataURI) {

    const binStr = atob(dataURI.split(',')[1]),
        len = binStr.length,
        arr = new Uint8Array(len),
        mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    for (let i = 0; i < len; i++) {
        arr[i] = binStr.charCodeAt(i);
    }

    return new Blob([arr], {
        type: mimeString
    });    
}

【讨论】:

    猜你喜欢
    • 2018-04-19
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    相关资源
    最近更新 更多