我的网站上有一个表单,可以根据输入为用户创建输出。 我想用此输出创建一个文本文件供用户下载(有浏览器下载提示,没有安全问题)。
有没有一种方法可以使用 Javascript/jQuery 来执行此操作,而无需先使用 PHP 在服务器上创建文件?
我可以使用某种Javascript对象作为虚拟文件,以便用户可以下载它(以解决没有真正的txt文件供用户从服务器下载的问题)吗?
最佳答案
您可以通过使用Blob
来实现这一点( browser support , polyfill )。看看这个example by @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>
关于javascript - jQuery/Javascript 创建一个文本文件供用户下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957758/