Writing Data to File in JavaScript
While JavaScript does not natively support file writing, it can still be achieved through the clever use of Blobs and URL.createObjectURL.
Browsers allow the creation of files using these methods. However, due to security concerns, direct saving of created files is prohibited. Instead, a download link can be provided to the user. Browsers may support the "download" attribute, which allows you to suggest a file name.
The code below provides a function to generate a text file from given text:
var makeTextFile = function (text) { var data = new Blob([text], {type: 'text/plain'}); return window.URL.createObjectURL(data); };
To initiate a download from a textarea, you can use the following code:
var create = document.getElementById('create'), textbox = document.getElementById('textbox'); create.addEventListener('click', function () { var link = document.createElement('a'); link.setAttribute('download', 'info.txt'); link.href = makeTextFile(textbox.value); document.body.appendChild(link); // simulate mouse click on link to start download var event = new MouseEvent('click'); link.dispatchEvent(event); document.body.removeChild(link); });
The above is the detailed content of How Can JavaScript Write Data to a File for Download?. For more information, please follow other related articles on the PHP Chinese website!