How to Check File Size Before Upload (HTML and jQuery)
- Details
- Written by Nam Ha Minh
- Last Updated on 23 September 2020   |   Print Email
In this short post, I will share with you a pretty simple way to limit size of upload file in a web form using HTML and Javascript/jQuery. Say you’re implementing file upload function in a web application, in which the users must not upload file larger than 5MB. If the user chooses to upload a file that exceeds 5MB, the browser will show an error message and reject form submission.
Given a file input in a HTML form like this:
<form> ... <input type="file" id="uploadFile" /> ... </form>
Then add the following jQuery code in the Javascript code section of the page as follows:
var MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB $(document).ready(function() { $('#uploadFile’).change(function() { fileSize = this.files[0].size; if (fileSize > MAX_FILE_SIZE) { this.setCustomValidity("File must not exceed 5 MB!"); this.reportValidity(); } else { this.setCustomValidity(""); } }); });
Then when the user picks a file larger than 5MB, the browser will report validation error immediately upon the file has been chosen:
Also when the user clicks the submit button, that warning is displayed as well. Pretty simple and effective, right?
I tested this file size checking code with different browsers like Chrome, Firefox and Edge. It works perfectly across browsers.
So I think it’s better to check size of upload file in the client side as shown in the above code example, which can eliminate unnecessary bandwidth to the server.
Java File Upload Tutorials:
- Java File Upload Example with Servlet 3.0 API
- Spring MVC File Upload Tutorial with Eclipse IDE
- Spring Boot File Upload Tutorial (Upload and Display Images)
Comments