子罕言利与命与仁

JS 写入到文件

//js写文件

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");

posted @ 2018-12-01 14:23  日出的幻景  阅读(10612)  评论(0编辑  收藏  举报
Top