If you want to create a simple web page that allows users to download a file using HTML, CSS, and JavaScript, you can follow the example below. This code will allow users to download a text file when they click a button.
Step 1: Create the HTML file
Create an index.html file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Download File Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Download File Example</h1>
<button id="downloadBtn">Download Text File</button>
</div>
<script src="script.js"></script>
</body>
</html>
Step 2: Add some CSS
Create a styles.css file to style your webpage:
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
text-align: center;
background-color: #fff;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
button {
padding: 10px 20px;
font-size: 16px;
border: none;
border-radius: 5px;
background-color: #007BFF;
color: white;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
Step 3: Add JavaScript for the download functionality
Create a script.js file to handle the download action:
document.getElementById('downloadBtn').addEventListener('click', function() {
const text = 'Hello, this is a sample text file.';
const blob = new Blob([text], { type: 'text/plain' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'sample.txt';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
Explanation:
- HTML: The structure consists of a container with a heading and a button that the user clicks to initiate the file download.
- CSS: Basic styling is provided for a better visual presentation.
- JavaScript:
- We create a blob from a string, which represents the content of the file.
- A temporary link element (
<a>) is created with a URL pointing to the blob.
- Automatically triggering a click on the link downloads the file.
- Finally, the temporary link is removed from the DOM.
How to Run:
- Create three files:
index.html, styles.css, and script.js in the same directory.
- Open
index.html in a web browser.
- Click the "Download Text File" button, and it will start downloading a file named
sample.txt with the specified text.
You can change the content of the text variable in script.js to customize the text file's contents.