How To Save Text As a File in HTML CSS and JavaScript?
Last Updated :
16 Aug, 2024
Improve
In this tutorial, we will learn how to save user input as a text file using HTML, CSS, and JavaScript. This can be particularly useful for web applications where users need to download their input or notes as a file.
Project Preview
We will build a simple web page that allows users to enter text in a text area and download it as a .txt file when they click a button.
Approach
- Make a basic structure of the project in HTML using h1 and h3 tag for main heading and sub-heading respectively.
- Make a textarea where user enter the text which they want to save as a text file using textarea element and make a button for save text file. Style all the elements through CSS.
- Add eventlistner on button when it clicks the file will download.
- Here we use Blob, type represents MIME type.
- Then, create Url.createObjectURL and create anchor tag and setting the attributes and their values.
Example: This code provides a web interface where users can enter text and save it as a file. The HTML sets up a text area and a button, the CSS styles the layout and elements, and the JavaScript handles the file creation and download process. When the button is clicked, the text is saved as a .txt file using a Blob.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Save Text As A File</title>
</head>
<body>
<div class="container">
<h1 class="gfg">GeeksforGeeks</h1>
<h3>Please enter the text you want to save as a file </h3>
<textarea name="text-area" id="text-area" cols="70" rows="20">
</textarea>
<button id="btn-id" class="btn">
Click here to save the text
</button>
</div>
<script src="script.js"></script>
</body>
</html>
/* style.css */
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
body {
font-family: 'Poppins', sans-serif;
margin: 0;
padding: 0;
}
.container {
height: 100vh;
display: flex;
flex-direction: column;
background-color: blanchedalmond;
justify-content: space-around;
align-items: center;
}
button {
height: 70px;
width: 400px;
border-radius: 45px;
background-color: rgb(242, 196, 242);
font-size: x-large;
}
.gfg {
color: green;
}
// script.js
let butto = document.querySelector("#btn-id")
let text = document.querySelector("#text-area")
// eventListener "click" on button
butto.addEventListener("click", () => {
let valueinput = text.value
let blobdtMIME =
new Blob([valueinput], { type: "text/plain" })
let url = URL.createObjectURL(blobdtMIME)
let anele = document.createElement("a")
anele.setAttribute("download", "Downloaded Successfully");
anele.href = url;
anele.click();
console.log(blobdtMIME)
})