How to Create a File Upload Button in HTML?
Uploading files through an HTML form is essential for many web applications, as it enables users to easily share documents, images, and other types of files. To create a file upload button in HTML, we can use the <input> element with type=”file” attribute inside a <form> tag.
Creating a Basic File Upload Button
Basic File Upload Button when the user selects a file using the file upload button, the name of the file will appear next to the button once selected.
Syntax
<input type="file">
<h1>Upload Your File</h1>
<form>
<input type="file" id="fileUpload" name="fileUpload">
<input type="submit" value="Upload">
</form>
Output

Basic File Upload Button
Customizing File Upload Button
User experience can be enhanced by customizing the appearance of the file upload button using CSS. For example, you can hide the default button and create a custom button for better styling. For this we style the <input> and the <label> tag.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.file-upload {
display: none;
}
.custom-button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
.custom-button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h1>Upload Your File</h1>
<form>
<input type="file" id="fileUpload" class="file-upload"
name="fileUpload">
<label for="fileUpload" class="custom-button">
Choose File
</label>
<input type="submit" value="Upload">
</form>
</body>
</html>
Output

Customizing the File Upload Button
Handling File Uploads in JavaScript
To provide feedback or further handle the file after selection, you can use JavaScript. This can be useful for displaying the file name or validating the file type before uploading.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.file-upload {
display: none;
}
.custom-button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
.custom-button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h1>Upload Your File</h1>
<form>
<input type="file" id="fileUpload" class="file-upload"
name="fileUpload">
<label for="fileUpload" class="custom-button">
Choose File
</label>
<input type="submit" value="Upload">
</form>
<p id="fileName"></p>
<script>
document.getElementById('fileUpload').addEventListener('change', function () {
let fileName = this.files[0] ? this.files[0].name : 'No file chosen';
document.getElementById('fileName').textContent = 'Selected file: ' + fileName;
});
</script>
</body>
</html>
Output

Handling File Uploads in JavaScript