Javascript 使用 JS 和 html5 从字符串创建文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10654971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:22:26  来源:igfitidea点击:

Create Text file from String using JS and html5

javascripthtmlfiledownloadcreatefile

提问by GreenGiant

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 \t Status\n'+ fileLIST[0][0].name+'\t'+fileLIST[0][1]+'\n';
    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 +'\t'+fileLIST[i][1] + '\n';}

    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.

我使用 chrome 作为我的浏览器。我也更喜欢 JS 或 HTML5 答案。

thank you in advance

先感谢您

采纳答案by GreenGiant

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

我最终改为使用此代码。它会创建一个链接来下载文件的 url。

     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.

此外,这种方式对网站的增加较少,使其成为连接速度较慢的较轻的网站。我的 html 有一个空的 div,它附加到其中。

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

回答by Anis Abboud

Convert your objectto a JSON string.

将您的转换object为 JSON 字符串。

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.
  1. 如果您已经有一个字符串,请跳过上面的步骤。
  2. 如果您不希望它的格式很好,请删除, 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();

回答by Joseph

I suggest you use a hidden iframeinstead of window.opento make it "a cleaner method"

我建议您使用隐藏iframe而不是window.open使其成为“更清洁的方法”

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

我相信这是text/octet-stream而不是text/json强制下载。而且据我所知,您不能以这种方式设置文件名。

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

但是,Chrome(我认为 18 岁以上)download<a>标签有一个属性,您可以指定文件名以及blob:用于 url 的名称。