Many of us faces problem while filtering the file in the server. Though it is easy to check for files in the server side but it is time consuming. So today we will use client server file uploading using jQuery.
In this tutorial we will restrict user to upload only pdf and image files.The pdf file size would be not more than 5M and the image file size would be within 1M. Any other files except this will not be uploaded.
Algorithm:
First we will take a input type file. The input file value would be reset on window load. Now when a user will try to upload a file we grab the file size and the extension of the file. Then we will check whether the file is image or pdf format. if this condition satisfies then we will proceed to the next step otherwise we will restrict the user and blank the input field value and show an error message. If the file format is ok then we will check for the file size (for images 1M and pdf 5M). If the condition satisfies the file will be kept in the input value for uploading, otherwise it will blank the input field value.
The source code is given below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File upload</title>
</head>
<body>
<div>
<input type="file" id="file0">
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
jQuery(document).ready(function () {
jQuery('#file0').val("");
jQuery("#file0").change(function ()
{
var iSize = jQuery("#file0")[0].files[0].size;
var ext = jQuery('#file0').val().split('.').pop().toLowerCase();
if (ext == "jpg" || ext == "png" || ext == "jpeg" || ext == "gif" || ext == "bmp") {
if (iSize > 1048576) {
jQuery('#file0').val("");
jQuery("#header").prepend('<div class="main_error" style="display:block;">The image file you have uploaded is too big (max. 1MB allowed).</div>');
setTimeout(function () {
jQuery('.main_error').hide();
}, 2000);
return false;
} else
{
//do code.
}
} else if (ext == "pdf")
{
if (iSize > 5242880) {
jQuery('#file0').val("");
jQuery("#header").prepend('<div class="main_error" style="display:block;">The PDF file you have uploaded is too big (max. 5MB allowed).</div>');
setTimeout(function () {
jQuery('.main_error').hide();
}, 2000);
return false;
} else
{
//do code.
}
} else
{
jQuery('#file0').val("");
jQuery("#header").prepend('<div class="main_error" style="display:block;">Not a valid file format.</div>');
setTimeout(function () {
jQuery('.main_error').hide();
}, 2000);
return false;
}
});
</script>
</body>
</html>
Hope this tutorial helped you a little and you have enjoyed it.