Search code examples
javascriptphpjqueryformsjquery-file-upload

how to check if array of file input fields have files uploaded?


I have an array of files and I want to be able to submit the form even if the file input fields are empty, but if they are not empty then check if its bigger than 5Mb. I could check if the file is bigger than 5Mb and if it is then it prevents form submit. but if the input file fields are empty the form will not allow me to submit. please help

  if (window.File && window.FileReader && window.FileList && window.Blob){
        //get the file size and file type from file input field
        var fsize = $('.upload_files')[0].files[0].size;

        if(fsize>5242880) //do something if file size more than 1 mb (1048576)
        {
            error_alert("file size is too big! please choose a smaller file");return false;
        }

        }

Solution

  • Here is the function which can be helpful to satisfy your needs. This function can work with n number of file objects and you can set it as a callback or can be called on any event as well. Please go through it.

    function checkFileSize() {
        $total_file_size = $file_size = 0 ;
        $file_selected = false ;
        $('input:file').each(function() {
            $file_size = 0 ;
            $obj = this.files[0] ;
    
            if (typeof($obj) == 'undefined'){
                $file_size = 0 ;
            }
            else {
                $file_selected = true ;
                $file_size = $obj.size ;
            }
            $total_file_size += $file_size ;
        }) ;
    
        if($file_selected) {
            if($total_file_size <= 5242880) {
                return true ;
            }
            alert('File size is greater than 5MB') ;
            return false ;
        }
        else {
            return false ;  
        }
    }
    

    You can tweak it as per your requirement. I wish it will work for you. Thanks, Have a great time ahead.