Posted inJavaScript / jQuery

How to validate upload file size and file extension using JavaScript?

Today, We want to share with you file upload size limit validation in javascript.In this post we will show you file upload validation in javascript, hear for Validation of file size while uploading using JavaScript / jQuery we will give you demo and example for implement.In this post, we will learn about input type file size limit javascript with an example.

How to validate upload file size and file extension using JavaScript ?

index.html


Note: Please select only image file (eg: .png, .jpeg, .jpg, .gif etc)
Max File size : 1MB allowed

No image uploaded

$(function() { $("#file").change(function () { if(fileExtValidate(this)) { if(fileSizeValidate(this)) { showImg(this); } } }); // File extension validation, Add more extension you want to allow var validExt = ".png, .gif, .jpeg, .jpg"; function fileExtValidate(fdata) { var filePath = fdata.value; var getFileExt = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase(); var pos = validExt.indexOf(getFileExt); if(pos < 0) { alert("This file is not allowed, please upload valid file."); return false; } else { return true; } } // file size validation // size in kb var maxSize = '1024'; function fileSizeValidate(fdata) { if (fdata.files && fdata.files[0]) { var fsize = fdata.files[0].size/1024; if(fsize > maxSize) { alert('Maximum file size exceed, This file size is: ' + fsize + "KB"); return false; } else { return true; } } } // display img preview before upload. function showImg(fdata) { if (fdata.files && fdata.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#img').attr('src', e.target.result); } reader.readAsDataURL(fdata.files[0]); } } });

Get File Size using JavaScript

index.html




    Get File Size Before Uploading in JavaScript - www.pakainfo.com



    

Get File Size using jQuery

index.html


    Get File Size using jQuery
    



    

I hope you get an idea about File upload size validation using jQuery with demo.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.

Leave a Reply

Your email address will not be published. Required fields are marked *

We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype