使用Angular 2和Node.js下载不适用于Firefox的PDF



我正在从节点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一起使用。

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

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

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

并在几秒钟后用setTimeout(() => 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
});    
}

最新更新