Gre*_*ant 9 javascript html5 file download createfile
我想从字符串创建一个文本文件.目前我正在使用一个函数,它接受一个数组并使其成为一个字符串然后使用该字符串我想创建一个用户下载的本地文本文件.我尝试过使用这种方法
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(); }
Run Code Online (Sandbox Code Playgroud)
我使用chrome作为我的浏览器.我也更喜欢JS或HTML5的答案.
先感谢您
Ani*_*oud 20
将您转换object为JSON字符串.
var json_string = JSON.stringify(object, undefined, 2);
Run Code Online (Sandbox Code Playgroud)
笔记:
, undefined, 2.创建下载链接并单击它:
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();
Run Code Online (Sandbox Code Playgroud)
BlobBuilder现在已经过时了.请改用:
https://developer.mozilla.org/en-US/docs/Web/API/Blob#Blob_constructor_example_usage
我最终使用了这段代码。它创建一个链接来下载文件的 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!';
}
Run Code Online (Sandbox Code Playgroud)
此外,这种方式给网站增加的内容更少,使其成为适合慢速连接的更轻量的网站。我的 html 有一个空 div,将其附加到其中。
<div class ='paginationLIST' id='pagination'></div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30173 次 |
| 最近记录: |