js 本地保存 json/txt 文件

时间:2020-04-04 11:37:27   收藏:0   阅读:111
    function download(filename, text) {
            var pom = document.createElement(‘a‘);
            pom.setAttribute(‘href‘, ‘data:text/plain;charset=utf-8,‘ + encodeURIComponent(text));
            pom.setAttribute(‘download‘, filename);
            if (document.createEvent) {
                var event = document.createEvent(‘MouseEvents‘);
                event.initEvent(‘click‘, true, true);
                pom.dispatchEvent(event);
            } else {
                pom.click();
            }
        }
        var data = {
            a:11,
            b:[{a:1,b:3}]
        }
        download("data.txt",JSON.stringify(data));

通过a标签的download属性,将数据保存到href属性中,模拟点击事件实现文件下载;

href属性中也可以直接防止下载文件的地址;

原文:https://www.cnblogs.com/recode-hyh/p/12630590.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!