programing

여러 파일 입력을 사용할 때 선택한 최대 파일을 제한하는 방법

copyandpastes 2021. 1. 15. 20:18
반응형

여러 파일 입력을 사용할 때 선택한 최대 파일을 제한하는 방법


사용할 때 <input type="file" multiple>사용자가 여러 파일을 선택할 수 있습니다.

하나는 선택할 수있는 파일 수에 대한 제한을 어떻게 설정합니까 (예 : 2 개)?


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");
        }
    });    
});​

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

그러나 클라이언트 측 유효성 검사를 아주 쉽게 우회 할 수 있으므로 서버 측에서도 확인해야합니다.


입력 트랙 변경시 선택한 파일 수 :

$("#image").on("change", function() {
    if ($("#image")[0].files.length > 2) {
        alert("You can select only 2 images");
    } else {
        $("#imageUploadForm").submit();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>On change of the input track how many files are selected:</strong>
<input name="image[]" id="image" type="file"  multiple="multiple" accept="image/jpg, image/jpeg" >


이렇게하면 파일 수가 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);
    }
  });
});

이를 위해 라이브러리 사용을 고려해야합니다. 라이브러리는 제한 등을 허용합니다.

They are also available at https://cdnjs.com/


if you want php you can count the array and just make an if statement like

if((int)count($_FILES['i_dont_know_whats_coming_next'] > 2)
      echo "error message";

Use two <input type=file> elements instead, without the multiple attribute.

ReferenceURL : https://stackoverflow.com/questions/10105411/how-to-limit-the-maximum-files-chosen-when-using-multiple-file-input

반응형