【问题标题】:Jquery image upload limit with multiple select带有多个选择的Jquery图像上传限制
【发布时间】:2014-09-11 14:58:26
【问题描述】:

我在上传图片时使用JavaScript来获取选定的文件扩展名。但是我想设置一次选择只上传四张图片的限制。我启用了multiple属性来选择多张图片。如何设置限制上传一次只有四个文件。我获取选定文件扩展名的 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>

【问题讨论】:

  • blueimp.github.io/jQuery-File-Upload你可以使用这个jQuery插件上传多个文件..
  • 我的上传功能运行良好@Kartikeya Khosla。
  • 我正在使用 UploadHandler php 类来上传图片。 @幸运

标签: javascript php jquery image-uploading


【解决方案1】:

据我所知,您需要在上传多个文件时限制文件数量,您可以使用小型 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');
   }
});

Demo

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

【讨论】:

  • 但这不会阻止选择超过四个图像。这只会显示验证消息。
  • 我不认为有一个 JavaScript 解决方案。因为它是基于窗口选择的。你必须设置一个标志来设置验证失败并阻止表单提交返回 false ..so 进行客户端验证,然后进行 ajax post 调用以使您的 Upload 处理程序调用以处理文件(如果通过验证)..
  • 感谢您的建议,我确实做到了。
【解决方案2】:

您可以使用上面的@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');
   }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 2016-09-22
    • 2021-03-31
    相关资源
    最近更新 更多