有什么方法可以在客户端创建一个文本文件,并提示用户下载它,而不与服务器进行任何交互? 我知道我不能直接写到他们的机器上(安全等),但是我可以创建并提示他们保存它吗?
当前回答
根据@Rick的回答,这真的很有帮助。
如果你想以这种方式共享字符串数据,你必须转义字符串数据:
$('a.download').attr('href', 'data:application/csv;charset=utf-8,'+ encodeURI(data));
` 抱歉,我不能评论@Rick的回答,因为我目前在StackOverflow的声誉很低。
分享了一个编辑建议,但被拒绝了。
其他回答
以下方法适用于IE11+、Firefox 25+和Chrome 30+浏览器:
<a id="export" class="myButton" download="" href="#">export</a>
<script>
function createDownloadLink(anchorSelector, str, fileName){
if(window.navigator.msSaveOrOpenBlob) {
var fileData = [str];
blobObject = new Blob(fileData);
$(anchorSelector).click(function(){
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
});
} else {
var url = "data:text/plain;charset=utf-8," + encodeURIComponent(str);
$(anchorSelector).attr("download", fileName);
$(anchorSelector).attr("href", url);
}
}
$(function () {
var str = "hi,file";
createDownloadLink("#export",str,"file.txt");
});
</script>
详见行动:http://jsfiddle.net/Kg7eA/
Firefox和Chrome支持数据URI导航,这允许我们通过导航到数据URI来创建文件,而IE出于安全考虑不支持它。
另一方面,IE有用于保存blob的API,可以用来创建和下载文件。
如前所述,filesaver是在客户端处理文件的一个很棒的包。但是,它不能很好地处理大文件。streamsave .js是一个可以处理大文件的替代解决方案(在FileServer.js中指向):
const fileStream = streamSaver.createWriteStream('filename.txt', size);
const writer = fileStream.getWriter();
for(var i = 0; i < 100; i++){
var uint8array = new TextEncoder("utf-8").encode("Plain Text");
writer.write(uint8array);
}
writer.close()
下面这个函数是有效的。
private createDownloadableCsvFile(fileName, content) {
let link = document.createElement("a");
link.download = fileName;
link.href = `data:application/octet-stream,${content}`;
return link;
}
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
download("hello.txt","This is the content of my file :)");
原文:https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server
您可以使用数据uri。浏览器支持各不相同;看到维基百科。例子:
<a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>
八位流是强制下载提示符。否则,它可能会在浏览器中打开。
对于CSV,您可以使用:
<a href="data:application/octet-stream,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV Octet</a>
试试jsFiddle演示。