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:

file size exceed error message

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:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment