jQuery check file type and size before upload

  • Post author:
  • Post category:jQuery

You can use jQuery to check the file type and size before uploading a file in an HTML form. To achieve this, you need to use JavaScript to handle the file input change event and validate the selected file. Here’s an example of how to do this:

$('.checkfile').live('change', function(){
    var fileUploadId = $(this).attr('id');
    ValidateExtension(fileUploadId);
});

function ValidateExtension(fileUploadId) {

    require(['jquery','Magento_Ui/js/modal/alert'], function($,alert) {
        var allowedFiles = [".doc" , ".pdf"];
        var fileUpload = document.getElementById(fileUploadId);
        var lblError = document.getElementById("lblError");

//lblError.innerHTML = '';

        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
        if (!regex.test(fileUpload.value.toLowerCase())) {
            alert({content: "Please upload files having extensions: " + allowedFiles.join(', ') + " only."});
            fileUpload.value = '';
            return false;
        }

        var maxFileSize = 2096000 /* 2MB */
        if (typeof (fileUpload.files) != "undefined") {
            var size = fileUpload.files[0].size;
            if(size > maxFileSize){
                alert({content: "File size should be less than 2MB."});
                fileUpload.value = '';
                return false;
            }
        }

        lblError.innerHTML = "";
        return true;
    });
}