繁体   English   中英

jQuery / Javascript创建文本文件供用户下载

[英]jQuery/Javascript create a text file for user download

我的网站上有一个表单,可以根据输入为用户创建输出。 我想用此输出创建一个文本文件供用户下载(带有浏览器下载提示,没有安全问题)。

有没有一种方法可以使用Javascript / jQuery而不先使用PHP在服务器上创建文件?

我可以使用某种Javascript对象作为虚拟文件,以便用户下载它(以解决用户没有从服务器下载真正的txt文件的问题)吗?

您可以通过使用Blob浏览器支持polyfill )来实现。 通过@UselessCode查看此示例

 (function () { var textFile = null, makeTextFile = function (text) { var data = new Blob([text], {type: 'text/plain'}); // If we are replacing a previously generated file we need to // manually revoke the object URL to avoid memory leaks. if (textFile !== null) { window.URL.revokeObjectURL(textFile); } textFile = window.URL.createObjectURL(data); return textFile; }; var create = document.getElementById('create'), textbox = document.getElementById('textbox'); create.addEventListener('click', function () { var link = document.getElementById('downloadlink'); link.href = makeTextFile(textbox.value); link.style.display = 'block'; }, false); })(); 
 <textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM