Create Text file from String using JS and html5

拈花ヽ惹草 提交于 2019-11-30 05:12:41

Convert your object to a JSON string.

var json_string = JSON.stringify(object, undefined, 2);

Notes:

  1. If you already have a string, skip the step above.
  2. If you don't want it to be formatted nicely, remove the , undefined, 2.

Create a download link and click it:

var link = document.createElement('a');
link.download = 'data.json';
var blob = new Blob([json_string], {type: 'text/plain'});
link.href = window.URL.createObjectURL(blob);
link.click();

i ended up using this code instead. it creates a link to download the url of the file.

     window.URL = window.webkitURL || window.URL;
    window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder ||       window.MozBlobBuilder;
    file = new WebKitBlobBuilder();
    file.append(output); 
    var a = document.getElementById("downloadFile");
    a.hidden = '';
    a.href = window.URL.createObjectURL(file.getBlob('text/plain'));
    a.download = 'filename.txt';
    a.textContent = 'Download file!';
}

also this way adds less to the website making it a lighter website for slow connections. my html has a empty div in which this appends to.

   <div class ='paginationLIST' id='pagination'></div>

I suggest you use a hidden iframe instead of window.open to make it "a cleaner method"

and I believe it's text/octet-stream and not text/json to force the download. And as far as I know, you can't set the file name this way.

However, Chrome (18+ I think) has a download attribute for its <a> tags which you can specify the name of the file along with using blob: for the url.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!