AS
Javascript
Create And Download A Text File
Il seguente esempio mostra un modo per predere del testo in input e renderlo disponibile come file di testo scaricabile dall'utente.
Codice
<!DOCTYPE html>
<html>
<head>
<script>
//https://stackoverflow.com/questions/3665115/
function download(filename, text)
{
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;cherset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
</script>
</head>
<body>
<div>Create and download a text file</div>
<form id="formId" target="_self">
<label>File name:</label>
<input id="nameId" type="text" name="name" value="test.txt">
<label>Text:</label>
<textarea id="textId" name="text"></textarea>
<input id="buttonId" type="button" value="Download">
</form>
<script>
function fnct_download()
{
var filename = document.getElementById("nameId").value;
var text = document.getElementById("textId").value;
download(filename, text);
document.getElementById("formId").submit;
}
document.getElementById("buttonId").addEventListener("click", fnct_download);
</script>
</body>
</html>
Risultato