Search code examples
javascriptphpjqueryimage-uploading

Jquery image upload limit with multiple select


I am using JavaScript to get the selected file extension when uploading image.But I want to set limit to upload only four images in one select.I have enabled the multiple attribute to select multiple images.How can I set limit to upload only four files at one time.My JavaScript code to get selected file extension is like :-

$(document).ready(function(){
  $('#fileupload').change(function(){
   var ext = $(this).val().split('.').pop().toLowerCase();
    if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
        alert("Please select an image.Only (gif, png, jpg, jpeg) types are allowed");
        return false;
      }
   });
});

My html form is like :-

<form method="POST">
  <input id="fileupload" class="image" type="file" name="files[]" multiple>
</form>

Solution

  • As far as I can get from your question that you need to limit the number of files while uploading multiple files, you can validate that on client side using a small javascript. All you need is just to access the length property of the input box for uploading the images.

    HTML:

    <form method="POST">
        <input id="fileupload" class="image" type="file" name="files[]" multiple="" />
        <div class="validation" style="display:none;"> Upload Max 4 Files allowed </div>
    </form>
    

    Javascript:

    $('#fileupload').change(function(){
       //get the input and the file list
       var input = document.getElementById('fileupload');
       if(input.files.length>4){
           $('.validation').css('display','block');
       }else{
           $('.validation').css('display','none');
       }
    });
    

    Demo

    Your other file name extension validation for letting only image files in upload remains the same.