In this article on File upload validations, you will see how to validate the File Type/Extension and File Size before uploading it to the server. In the web application, from the security point of view file validation is the most important parameter that needs to be considered by each developer especially when doing the file upload. The validations can be either client-side or server-side or maybe both.
This Article demonstrates the client-side validation using jQuery. Let’s start it.
Table of Contents
File Type (Extension) Validation
We can easily validate the file type by extracting the file extension with the allowed file types using jQuery.
Example of File Type Validation
Below is the sample example for the file type validation. In this example, we upload files having extensions .jpeg/.jpg/.png/.gif only. Here file type validation will be checked on the change event of the HTML input element.
<!DOCTYPE html>
<html>
<head>
<title>
File type validation while uploading using jQuery
</title>
<!-- jQuery library script import -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
body{
text-align:center;
}
</style>
</head>
<body>
<h1>File type validation while uploading using jQuery</h1>
<p>Upload an image (.jpg,.jpeg,.png,.gif)</p>
<!-- input element to choose a file for uploading -->
<input type="file" id="file-upload" />
<script>
/* this function will call when page loaded successfully */
$(document).ready(function(){
/* this function will call when onchange event fired */
$("#file-upload").on("change",function(){
/* current this object refer to input element */
var $input = $(this);
/* collect list of files choosen */
var files = $input[0].files;
var filename = files[0].name;
/* getting file extenstion eg- .jpg,.png, etc */
var extension = filename.substr(filename.lastIndexOf("."));
/* define allowed file types */
var allowedExtensionsRegx = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
/* testing extension with regular expression */
var isAllowed = allowedExtensionsRegx.test(extension);
if(isAllowed){
alert("File type is valid for the upload");
/* file upload logic goes here... */
}else{
alert("Invalid File Type.");
return false;
}
});
});
</script>
</body>
</html>
Let’s understand the above code implementation with sample points:
- In order to use jQuery, we need to import jQuery library script. eg- a jQuery CDN we imported here, <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
- An HTML
<input>
element is defined with attribute type=”file” to choose a file for uploading. - Here $(document).ready(function(){…}); will be called when HTML page has been loaded successfully.
- Now on the change event of HTML
<input>
element, the validation logic code will execute. - Using $(this), getting the jQuery file input element object.
- Using $(this)[0].files, getting the list of files which are choosen by the user.
- Using files[0].name, getting the name of the file with extension (eg- wallpager.png).
- Defining regular expression allowedExtensionsRegx variable with allowed file types(.JPG, .JPEG, .PNG, .GIF only).
- Using the
test()
function, checking wether the file type is allowed or not. It returns boolean value true or false.
Preview & Live Demo
Working With Multiple Files Upload
Sometimes based on project requirements we required multiple files to upload at a time. This scenario can be handled easily with few modifications in the above sample example.
Let’s understand the required code modification:
1.) In the HTML <input>
element, add the multiple
attribute. The multiple
attribute is used to allow choosing the multiple files at a time.
See the below image to understand how it can be added to an HTML <input>
element:
2.) The next modification is required in $("#file-upload").on("change",function(){...})
function. Inside this function, $(this)[0].files will return the Array of files object. So as it is an Array, we can iterate it through a for loop and validate the file type one by one for each file.
See the below-modified code:
/* this function will call when onchange event fired */
$("#file-upload").on("change",function(){
/* current this object refer to input element */
var $input = $(this);
/* collect list of files choosen */
var files = $input[0].files;
for(var i=0;i<files.length;i++){
var filename = files[i].name;
/* getting file extenstion eg- .jpg,.png, etc */
var extension = filename.substr(filename.lastIndexOf("."));
/* define allowed file types */
var allowedExtensionsRegx = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
/* testing extension with regular expression */
var isAllowed = allowedExtensionsRegx.test(extension);
if(isAllowed){
alert("File type is valid for the upload");
/* file upload logic goes here... */
}else{
alert("Invalid File Type.");
}
}
});
File Size Validation
The size of the uploading file can also be validated easily by using jQuery.
Example of File Size Validation
Below is the sample example for the file size validation. In this example, we upload files having a size less than or equals to 2MB only. Here file size validation will be checked on the change event of the HTML input element.
<!DOCTYPE html>
<html>
<head>
<title>
File size validation while uploading using jQuery
</title>
<!-- jQuery library script import -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
body{
text-align:center;
}
</style>
</head>
<body>
<h1>File size validation while uploading using jQuery</h1>
<p>Upload a file (size less than or equal to 2MB) only</p>
<!-- input element to choose a file for uploading -->
<input type="file" id="file-upload" />
<script>
/* this function will call when page has been loaded successfully */
$(document).ready(function(){
/* this function will call when onchange event fired */
$("#file-upload").on("change",function(){
/* current this object refer to input element */
var $input = $(this);
/* collect list of files choosen */
var files = $input[0].files;
var fileSize = files[0].size;
/* 1024 = 1MB */
var size = Math.round((fileSize / 1024));
/* checking for less than or equals to 2MB file size */
if (size <= 2*1024) {
alert("Valid file size");
/* file uploading code goes here... */
} else {
alert(
"Invalid file size, please select a file less than or equal to 2mb size");
}
});
});
</script>
</body>
</html>
Let’s understand the above code implementation with sample points:
- To use jQuery, we need to import jQuery library script. eg- a jQuery CDN we imported here, <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
- An HTML
<input>
element is defined with attribute type=”file” to choose a file for uploading. - Here $(document).ready(function(){…}); function will be called when HTML page has been loaded successfully.
- Now on the change event of HTML
<input>
element, the validation logic code will execute. - Using $(this), getting the jQuery file input element object.
- Using $(this)[0].files, getting the list of files which are choosen by the user.
- Using files[0].size, getting the size of the file in bytes format.
- Calculating the file size in rounded figure using
Math.round()
function in MB. - Checking wether the file size is less than or equals to 2MB or not.
Preview & Live Demo
Working With Multiple Files Upload
In this case also when we are required to work with multiple files upload, we can handle it easily with few modifications in the above sample example.
Let's understand the required code modification:
1.) In the HTML <input>
element, add the multiple
attribute. The multiple
attribute is used to allow choosing the multiple files at a time.
See the below image to understand how it can be added to an HTML <input>
element:
2.) The next modification is required in $("#file-upload").on("change",function(){...})
function. Inside this function, $(this)[0].files will return the Array of files object. So here also, we can iterate it through a for loop and validate the file size one by one for each file.
See the below-modified code:
/* this function will call when onchange event fired */
$("#file-upload").on("change",function(){
/* current this object refer to input element */
var $input = $(this);
/* collect list of files choosen */
var files = $input[0].files;
/* iterating over the files array */
for(var i=0; i<files.length; i++){
var fileSize = files[i].size;
/* 1024 = 1MB */
var size = Math.round((fileSize / 1024));
/* checking for less than or equals to 2MB file size */
if (size <= 2*1024) {
alert("Valid file size");
/* file uploading code goes here... */
} else {
alert(
"Invalid file size, please select a file less than or equal to 2mb size");
}
}
});
Conclusion
In this article, you have learned how to validate file type and file size before uploading it to the server using jQuery. You have also learned how to work with multiple file upload validations.
Also, learn how to validate file upload using Javascript
If you want to learn how to do file upload to the server with server-side file validation in Java you can visit the below links:
Spring Boot File Upload with Advance Progress bar in Ajax
File Upload in Java Servlet Example