Skip to content

Instantly share code, notes, and snippets.

@johnsie
Created April 23, 2025 10:02
Show Gist options
  • Save johnsie/6c3afae9ad5c14b5161912ca9b539cf0 to your computer and use it in GitHub Desktop.
Save johnsie/6c3afae9ad5c14b5161912ca9b539cf0 to your computer and use it in GitHub Desktop.
<form asp-action="Upload" method="post" enctype="multipart/form-data">
<input type="file" name="File" id="fileInput" />
<span id="fileError" class="text-danger"></span>
<button type="submit">Upload</button>
</form>
<script>
document.getElementById('fileInput').addEventListener('change', function () {
const file = this.files[0];
const maxSizeInBytes = 5 * 1024 * 1024; // 5 MB
const errorElement = document.getElementById('fileError');
errorElement.textContent = ""; // Clear old errors
if (file && file.size > maxSizeInBytes) {
errorElement.textContent = "The selected file is too large (max 5MB).";
this.value = ""; // Clear file input so user can choose again
}
});
</script>
✅ What This Does
Prevents users from even attempting to upload huge files
Gives instant feedback
Saves bandwidth and avoids 400 / 413 errors
🔄 Optional: Block the form submission completely (extra safety)
If you're worried users might try to submit the form some other way (e.g. via keyboard or script), you can prevent form submission:
html
Copy
Edit
<form id="uploadForm" ...>
...
</form>
<script>
document.getElementById('uploadForm').addEventListener('submit', function (e) {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const maxSize = 5 * 1024 * 1024;
if (file && file.size > maxSize) {
e.preventDefault();
document.getElementById('fileError').textContent = "The selected file is too large.";
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment