Home >Web Front-end >JS Tutorial >How Can I Verify File Size Before Uploading with JavaScript?
Verifying File Size Before Uploading with JavaScript
When dealing with file uploads, it's crucial to ensure that the file size meets certain constraints. JavaScript provides an elegant solution for this with the File API.
Solution:
To validate file size before uploading, utilize the following code:
// Setup event listener for 'Load' button click document.getElementById("btnLoad").addEventListener("click", function () { // Verify browser support for FileReader if (!window.FileReader) { console.log("File API not supported."); return; } // Retrieve the file from the file input var input = document.getElementById("fileinput"); var file = input.files[0]; // Validate file size if (!file) { console.log("No file selected."); } else { console.log("File " + file.name + " is " + file.size + " bytes in size."); } });
Explanation:
The above is the detailed content of How Can I Verify File Size Before Uploading with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!