JavaScript

Crea e scarica un file di testo

by Andrea Spera

Il seguente esempio mostra un modo per predere del testo in input e renderlo disponibile come file di testo scaricabile dall'utente.
La funzione download crea e avvia il download di un file di testo con il nome e il contenuto forniti.
  • document.createElement('a'): crea un elemento <a> (link) in modo dinamico.
  • element.setAttribute('href', ...): imposta l'attributo href con i dati del file da scaricare, usando un URI per i contenuti di testo.
  • element.setAttribute('download', filename): imposta il nome del file da scaricare.
  • element.click(): simula il clic sul link per avviare il download.
Codice
<!DOCTYPE html>
<html>
<head>
<script>
//https://stackoverflow.com/questions/3665115/
function download(filename, text)
	{
	let 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()
	{
	let filename = document.getElementById("nameId").value;
	let text = document.getElementById("textId").value;
	download(filename, text);
	document.getElementById("formId").submit;
	}
document.getElementById("buttonId").addEventListener("click", fnct_download);
</script>
</body>
</html>
Output