Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

javascript - Create Text file from String using JS and html5

i want to create a text file from a string. currently i am using a function which takes an array and makes it into a string then using that string i want to create a local text file the user downloads. i have tried using this method

   function createFile(){ //creates a file using the fileLIST list 
    var output= 'Name  Status
'+ fileLIST[0][0].name+''+fileLIST[0][1]+'
';
    var Previous = fileLIST[0];
    for (var i=1; i<fileLIST.length; i++)
        if (fileLIST[i][1] =='none' || fileLIST[i][1] == Previous[1])
            continue
        else {
            Previous = fileLIST[i]
            output = output + fileLIST[i][0].name +''+fileLIST[i][1] + '
';}

    window.open("data:text/json;charset=utf-8," + escape(output));//should create file
    display();  }

i am using chrome as my browser. also i would prefer JS or HTML5 answer.

thank you in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...