如何限制使用多个文件输入时选择的最大文件数

rjm*_*mcb 55 html file

使用<input type="file" multiple>时,用户可以选择多个文件.

如何设置可以选择多少文件的限制,例如两个?

Cur*_*urt 53

您可以运行一些jQuery客户端验证来检查:

$(function(){
    $("input[type='submit']").click(function(){
        var $fileUpload = $("input[type='file']");
        if (parseInt($fileUpload.get(0).files.length)>2){
         alert("You can only upload a maximum of 2 files");
        }
    });    
});?
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Curt/u4NuH/

但请记住检查服务器端,因为客户端验证可以很容易地被绕过.

  • 我不太明白为什么将此代码标记为正确答案。它确实会检查上传文件的数量,但是不会禁用表单提交。jsfiddle代码没有带有定义的动作属性的表单标签,并且看起来似乎不错,但是,如果我们通过添加表单标签对其进行扩展,它将在警报出现后立即提交表单。 (6认同)
  • @David 主要是因为人们到处复制和粘贴内容。那已经6年了。 (3认同)

小智 8

$("#image").on("change", function() {
    if ($("#image")[0].files.length > 2) {
        alert("You can select only 2 images");
    } else {
        $("#imageUploadForm").submit();
    }
});
Run Code Online (Sandbox Code Playgroud)


Dav*_*vid 8

如果文件数量大于 max_file_number,这应该可以工作并保护您的表单不被提交。

$(function() {

  var // Define maximum number of files.
      max_file_number = 3,
      // Define your form id or class or just tag.
      $form = $('form'), 
      // Define your upload field class or id or tag.
      $file_upload = $('#image_upload', $form), 
      // Define your submit class or id or tag.
      $button = $('.submit', $form); 

  // Disable submit button on page ready.
  $button.prop('disabled', 'disabled');

  $file_upload.on('change', function () {
    var number_of_images = $(this)[0].files.length;
    if (number_of_images > max_file_number) {
      alert(`You can upload maximum ${max_file_number} files.`);
      $(this).val('');
      $button.prop('disabled', 'disabled');
    } else {
      $button.prop('disabled', false);
    }
  });
});
Run Code Online (Sandbox Code Playgroud)


Enr*_*que 7

JS的另一种可能解决方案

function onSelect(e) {
    if (e.files.length > 5) {
        alert("Only 5 files accepted.");
        e.preventDefault();
    }
}
Run Code Online (Sandbox Code Playgroud)