admin管理员组文章数量:1393083
I have a form on my website that creates output for the user based on the input. I want to create a text file with this output for the user to download (with browser download prompt, no security problems).
Is there a way to do this with Javascript/jQuery without using PHP to create the file on the server first?
Can I use some kind of Javascript object to serve as a dummy-file so that the user can download it (to solve the problem that there isn't a real txt file for the user to download from the server)?
I have a form on my website that creates output for the user based on the input. I want to create a text file with this output for the user to download (with browser download prompt, no security problems).
Is there a way to do this with Javascript/jQuery without using PHP to create the file on the server first?
Can I use some kind of Javascript object to serve as a dummy-file so that the user can download it (to solve the problem that there isn't a real txt file for the user to download from the server)?
Share Improve this question edited Oct 10, 2016 at 12:10 John Ellis asked Oct 10, 2016 at 11:57 John EllisJohn Ellis 351 gold badge1 silver badge8 bronze badges 2- Only with Javascript or JQuery it's not possible i think. You need server side script – vamsi Commented Oct 10, 2016 at 12:04
- For older browsers (and simple plaintext files) you can open a window in that document mode. Take a look at this answer http://stackoverflow./questions/7338640/document-opentext-plain-formatting-ignored-in-webkit-safari-chrome – Emil S. Jørgensen Commented Oct 10, 2016 at 12:14
1 Answer
Reset to default 3You can achieve that by using Blob
(browser support, polyfill). Check out this 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>
本文标签: jQueryJavascript create a text file for user downloadStack Overflow
版权声明:本文标题:jQueryJavascript create a text file for user download - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744701556a2620592.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论