我尝试使用以下代码在设备“ mac os”上下载json对象。结果是在浏览器上显示json正文,尽管它可以与其他操作系统“ android,windows”一起使用。
是否有其他解决方案?
function downloadJsonFile(fileName, jsonObject) {
let fileContents = JSON.stringify(jsonObject);
let data = "text/json;charset=utf-8," + encodeURIComponent(fileContents);
let a = document.createElement('a');
a.href = 'data:' + data;
a.download = fileName + '.json';
a.click();
}
答案 0 :(得分:1)
尝试这样的事情:
演示----> Download Json
download(strData, strFileName, strMimeType) {
strData = JSON.stringify(strData);
var D = document,
A = arguments,
a = D.createElement("a"),
n = A[1];
a.href = "data:" + strMimeType + "charset=utf-8," + (strData);
if ('download' in a) {
a.setAttribute("download", n);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function () {
var e = D.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
D.body.removeChild(a);
}, 66);
return true;
};
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (strData);
setTimeout(function () {
D.body.removeChild(f);
}, 333);
return true;
}