Jquery图像上传限制与多重选择


Jquery image upload limit with multiple select

我使用JavaScript在上传图像时获得所选的文件扩展名。但我想设置限制,一次只能上传四张图片。我启用了multiple属性来选择多个图像。如何设置一次只能上传4个文件的限制?我的JavaScript代码得到选择的文件扩展名是这样的:-

$(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;
      }
   });
});

我的html表单是:-

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

就我所能从你的问题中得到的,你需要在上传多个文件时限制文件的数量,你可以使用一个小的javascript在客户端验证。您只需要访问输入框的length属性即可上传图片。

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');
   }
});

您的其他文件扩展名验证只允许上传图像文件保持不变。

您可以使用上面的@lucky建议,并添加一个禁用按钮功能,仅在满足这些条件时显示

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