Download file with JavaScript
by dkamburov
HTML
<form onsubmit="onFormSubmit(); return false;">
<p>
<label for="demo_filename">File name:</label><br>
<input id="demo_filename" type="text">
</p>
<p>
<label for="demo_content">Content:</label><br>
<textarea id="demo_content"></textarea>
</p>
<button type="button">Download</button>
</form>
JavaScript
function downloadFile(data="", fileName="test.txt", type="text/plain") {
// Create an invisible A element
const a = document.createElement("a");
a.style.display = "none";
document.body.appendChild(a);
// Set the HREF to a Blob representation of the data to be downloaded
a.href = window.URL.createObjectURL(
new Blob([data], { type })
);
// Use download attribute to set set desired file name
a.setAttribute("download", fileName);
// Trigger the download by simulating click
a.click();
// Cleanup
document.body.removeChild(a);
}
function onFormSubmit() {
downloadFile(
document.getElementById("demo_content").value,
document.getElementById("demo_filename").value
);
}