我尝试使用以下代码在客户端创建和下载文件:
function downloadFile(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.click();
}
虽然这只适用于chrome。在safari和IE上没有任何事情发生。我怎样才能使它发挥作用?
答案 0 :(得分:0)
不确定你是否已经想到了这个但是为了在safari中工作,你需要在创建的元素上创建一个事件和调度,如下所示:
var downloadLink = document.createElement('a');
downloadLink.setAttribute('href', 'data:application/octet;charset=utf-8,' + encodeURIComponent(data));
downloadLink.setAttribute('download', fileName);
downloadLink.style.display = "none";
downloadLink.onclick = function (event) {
document.body.removeChild(event.target);
};
var clk = document.createEvent("MouseEvent");
clk.initEvent("click", true, true);
downloadLink.dispatchEvent(clk);
document.body.appendChild(downloadLink);
downloadLink.dispatchEvent(clk);`
答案 1 :(得分:-1)
我用它以CSV / excel格式保存我的文件,并在chrome / IE / Safari中工作 参考并进行必要的更改
var fileName = name + "["+ name1 +"]";
var uri = 'data:text/csv;charset=utf-8,' + escape(finalResult);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
location.reload();