我一直在寻找一种方法来启动仅存在于用户浏览器上执行的代码中的数据文件下载(而不是从服务器启动下载),并在过程中指示文件名。
搜索 StackOverflow 会发现一些有前途的帖子,但它们并不能满足我的需要。
This answer 与 IE 不兼容,并且不允许指定文件名。
This问题提供了几种启动下载的方法,但允许指定文件名的答案不兼容 IE,需要用户交互,而其他答案则不允许指定文件名。
有没有一种方法可以从 JavaScript 启动文件下载:
- 下载客户端数据
- 不需要用户手动启动下载
- 允许指定下载文件的文件名
最佳答案
经过大量搜索并尝试了来自不同地方的方法,我得出了以下结论。
tryAnchorDownload()
方法应该适用于现代版本的 FireFox 和 Chrome,并且是提供的代码的清理版本 in this forum post .
trySaveAsDownload()
方法理论上应该适用于任何主要的现代浏览器,尽管 Safari 可能不遵守指定的文件名。它需要 FileSaver.js图书馆和一些浏览器可能需要 Blob.js polyfill.
你可以像这样调用主函数:
initiateFileDownload(bytes, "myFile.txt");
其中 bytes
是文件字节的 Uint8Array
。
function byteArrayToBase64(bytes) {
var chArray = Array.prototype.map.call(bytes,
function (byte) { return String.fromCharCode(byte); });
return window.btoa(chArray.join(""));
}
var octetStreamMimeType = "application/octet-stream";
function tryAnchorDownload(fileBytes, fileName) {
var aElement = document.createElement("a"),
event;
if ("download" in aElement) {
aElement.setAttribute("download", fileName);
aElement.href = "data:" + octetStreamMimeType +
";base64," + byteArrayToBase64(fileBytes);
document.body.appendChild(aElement);
event = document.createEvent("MouseEvents");
event.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0,
false, false, false, false, 0, null);
aElement.dispatchEvent(event);
document.body.removeChild(aElement);
return true;
}
return false;
}
function trySaveAsDownload(fileBytes, fileName) {
var blob;
if (window.saveAs) {
blob = new Blob([fileBytes], { type: octetStreamMimeType });
saveAs(blob, fileName);
return true;
}
return false;
}
// fileBytes is a Uint8Array
function initiateFileDownload(fileBytes, fileName) {
return tryAnchorDownload(fileBytes, fileName) ||
trySaveAsDownload(fileBytes, fileName);
}
可以找到上面的 byteArrayToBase64()
函数的更彻底(并且可能更有效)的替代方法 on MDN .
关于javascript - 如何启动客户端数据的文件下载并指定其文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25445351/