fileUrl:根据元素 ID 获取相应的 URL

fileUrl: function (elementId) {
var url;
if (navigator.userAgent.indexOf("MSIE") >= 1) {
url = document.getElementById(elementId).value;
} else if (navigator.userAgent.indexOf("Firefox") > 0 || navigator.userAgent.indexOf("Chrome") > 0) {
url = window.URL.createObjectURL(document.getElementById(elementId).files.item(0));
}
return url;
},
saveDataToFile:保存数据到文件


saveDataToFile: function (data, filename) {
"use strict";
if (!data || !filename) {
console.error("缺少输入参数:data 和 filename 是必需的。");
return;
}
var view = window || global,
doc = view.document,
get_URL = function () {
return view.URL || view.webkitURL || view;
},
create_object_url = function (data) {
if (typeof Blob === "function") {
return get_URL().createObjectURL(new Blob([data], { type: "octet/stream" }));
} else if (typeof data === "object" && data instanceof String) {
return "data:application/octet-stream;base64," + btoa(data);
} else if (typeof data === "object") {
return get_URL().createObjectURL(data);
} else {
throw new Error("无法为类型为 " + typeof data + " 的项目创建 URL。");
}
},
download_file = function (url, filename) {
var support_save_link = "download" in doc.createElementNS("http://www.w3.org/1999/xhtml", "a");
if (support_save_link) {
var link = document.createElement("a");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} else {
location.href = url;
}
};
if (typeof data === "object" || data instanceof Blob) {
var object_url = get_URL().createObjectURL(data);
download_file(object_url, filename);
revoke(object_url);
}
else if (typeof data === "string") {
var url = create_object_url(data);
download_file(url, filename);
}
else {
console.error("无效的输入参数:只有 Blob 对象或 String 文本受支持。");
return;
}
function revoke(url) {
setTimeout(function () {
get_URL().revokeObjectURL(url);
}, 1000);
if (typeof InstallTrigger !== "undefined") {
console.warn(
"[Firefox] 必须手动启用“另存为”对话框提示。 https://support.mozilla.org/zh-CN/kb/how-to-download-and-install-firefox-on-windows/"
);
}
}
},