我正在尝试创建一个excel文件,该文件可以从Firefox和Chrome的角度2+环境中下载。我让它在firefox中运行得很好,但是我尝试的每一件事都不能在Chrome中运行--它下载文件,但是当你打开它时它会抛出一个错误-- "Excel不能打开这个文件,因为文件格式或文件扩展名无效。“
我试图将我的帖子responseType设置为'arrayBuffer‘,然后创建一个blob然后下载,但没有成功。我试过responseType : 1)'blob‘2)'blob’如'json‘3)'blob’
以那种方式传递给我的组件。Chrome上似乎什么都不起作用,不过火狐上的一切都能工作。
以下是我用来尝试让Chrome打开这个excel的一些功能。
downloadBlob(data: Blob, fileName: string) {
//output file name
//detect whether the browser is IE/Edge or another browser
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
//To IE or Edge browser, using msSaveorOpenBlob method to download file.
window.navigator.msSaveOrOpenBlob(data, fileName);
} else {
//To another browser, create a tag to downlad file.
const url = window.URL.createObjectURL(data);
const a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
}
blobToFile(data: Blob, fileName: string) {
const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';
const url = window.URL.createObjectURL(data);
a.href = url; a.download = fileName; a.click();
window.URL.revokeObjectURL(url);
}
downloadArray(data, fileName: string) {
var blob = new window.Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
window.URL = window.URL || window.webkitURL;
var url = window.URL.createObjectURL(blob);
window.location.href = url;
}
我甚至试着用FileSaver.js插件来保存我的blob
saveAs('blob', 'filename');
但是当从铬打开的时候,所有的东西都看不出来。如有任何建议,将不胜感激。
发布于 2022-01-27 17:22:55
考虑删除revokeObjectURL()
。此测试在Chrome:https://batman.dev/static/70844902/中工作和下载。
function downloadBuffer(arrayBuffer, fileName) {
const a = document.createElement('a')
a.href = URL.createObjectURL(new Blob(
[ arrayBuffer ],
{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }
))
a.download = fileName
a.click()
}
https://stackoverflow.com/questions/70844902
复制