Create and Download Text Files with JavaScript
In this blog post, we’ll explore a simple way to create and download text files directly from your web browser using JavaScript. This technique can be particularly useful for generating reports, saving user input, or exporting data in a text format without the need for server-side processing.
How It Works
The code snippet below demonstrates how to create a text file from user input in a textarea and allow the user to download it with a click of a button. The implementation uses the Blob object and the URL.createObjectURL method to generate a downloadable file link.
Code Explanation
Here’s the complete code you’ll need:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Text File</title>
</head>
<body>
<textarea id="textbox">Type something here</textarea>
<button id="create">Create file</button>
<a download="info.txt" id="downloadlink" style="display: none">Download</a>
<script>
(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);
})();
</script>
</body>
</html>
How to Use the Code
- HTML Structure: The code begins with a simple HTML structure that includes a
<textarea>
for user input, a<button>
to trigger the file creation, and an<a>
element that will serve as the download link. - JavaScript Functionality:
- The
makeTextFile
function creates a new Blob containing the text from the textarea. - It revokes any previously generated object URL to free up memory.
- The
create
button has an event listener that, when clicked, generates the text file and updates the download link to point to the newly created Blob.
- The
- Download Link: Once the file is created, the link becomes visible, allowing the user to download the file named
info.txt
.
Try It Out
To see the code in action, simply copy it into an HTML file and open it in your web browser. Type any text into the textarea, click “Create file,” and then download your text file.
This approach is a great way to enhance user experience by allowing users to save their data without needing to involve server-side scripting.
Happy coding!