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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744701556a4588806.html
评论列表(0条)