码迷,mamicode.com
首页 > Web开发 > 详细

JS 由前端保存到文件

时间:2019-09-01 14:30:40      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:href   pre   dde   end   function   div   dos   string   ati   

function doSave(value, type, name) {
    var blob;
    if (typeof window.Blob == "function") {
        blob = new Blob([value], {type: type});
    } else {
        var BlobBuilder = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder;
        var bb = new BlobBuilder();
        bb.append(value);
        blob = bb.getBlob(type);
    }
    var URL = window.URL || window.webkitURL;
    var bloburl = URL.createObjectURL(blob);
    var anchor = document.createElement("a");
    if (‘download‘ in anchor) {
        anchor.style.visibility = "hidden";
        anchor.href = bloburl;
        anchor.download = name;
        document.body.appendChild(anchor);
        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", true, true);
        anchor.dispatchEvent(evt);
        document.body.removeChild(anchor);
    } else if (navigator.msSaveBlob) {
        navigator.msSaveBlob(blob, name);
    } else {
        location.href = bloburl;
    }
}

var test = {
    a: [1, 2],
    b: [3, 4]
}
doSave(JSON.stringify(test), "text/latex", "hello.txt");

 

JS 由前端保存到文件

标签:href   pre   dde   end   function   div   dos   string   ati   

原文地址:https://www.cnblogs.com/413xiaol/p/11442103.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!