Checking File Size Before Upload in JavaScript
With JavaScript's advanced functionality, it's possible to validate file size before uploading. This ensures adherence to size constraints, preventing server-side issues or user frustrations due to large file sizes.
Solution: The File API
The File API provides an easy way to interact with files on the client side. Here's a practical example:
document.getElementById("btnLoad").addEventListener("click", function showFileSize() { // Check for browser support if (!window.FileReader) { console.log("File API not supported"); return; } var input = document.getElementById("fileinput"); // Check for selected file if (!input.files || !input.files[0]) { addPara("Select a file first"); } else { var file = input.files[0]; addPara("File " + file.name + " is " + file.size + " bytes in size"); } });
This script:
By integrating this script into your upload form, you can effectively prevent large file submissions and provide a seamless user experience.
The above is the detailed content of How Can I Check File Size Before Uploading with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!