Как включить кнопку отправки до состояния в загрузчике нескольких файлов? - PullRequest
1 голос
/ 02 мая 2019

Я делаю WebApp, где люди будут загружать 2 изображения, которые мне нужно пройти через код Python.По этой причине я хочу разрешить им отправлять его только при загрузке 2 изображений.

Я читаю другие сообщения, такие как:

Как отключить кнопку отправки, пока файл не будетвыбранный

Включить кнопку отправки после загрузки более 1 файла

Но я не могу экстраполировать ее на мой случай:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="https://unpkg.com/file-upload-with-preview@3.4.3/dist/file-upload-with-preview.min.css">
</head>


<body>
  <!-- Uploader -->
<div class="custom-file-container" data-upload-id="myImage">
    <label>Upload your images <a href="javascript:void(0)" class="custom-file-container__image-clear" title="Clear Image">&times;</a></label>

    <label class="custom-file-container__custom-file" >
      <form id="upload-form" action="{{url_for('upload')}}" method="POST" enctype="multipart/form-data">
      <input type="file" class="custom-file-container__custom-file__custom-file-input" accept="image/*" aria-label="Choose File" multiple>
      <input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
      <span class="custom-file-container__custom-file__custom-file-control"></span>
    </label>
    <div class="custom-file-container__image-preview"></div>
</div>
<input type="submit" name="send" disabled/>
</div>


<script src="https://unpkg.com/file-upload-with-preview@3.4.3/dist/file-upload-with-preview.min.js"></script>

<script>
      var upload = new FileUploadWithPreview('myImage', {showDeleteButtonOnImages: true, text: {chooseFile: 'Nom del fitxer', browse: 'Examina'}})
</script>

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>

<script>

$(document).ready(
    function(){
        $('input:file').change(
            function(){
                if ($(this).val()) {
                    $('input:submit').attr('disabled',false);; 
                } 
            }
            );
    });

</script>

</body>
</html>

Последний добавленный скрипт - это решение, приведенное в первой ссылке, которое работает должным образом, но это не то, что мне нужно.

Код загрузки файла взят из https://github.com/promosis/file-upload-with-preview,, где я виделчто есть метод selectedFilesCount, который может быть полезен.

Спасибо за ваше время и извините, если вы видите какую-то чепуху в моем коде, но я новичок в этих языках ...

1 Ответ

1 голос
/ 02 мая 2019

Вы можете подключиться к upload.cachedFileArray из объекта загрузки, чтобы проверить длину array, чтобы убедиться, что для загрузки выбрано 2 файла. Это проверяется с помощью функции toggle (), которая связана с window event listeners fileUploadWithPreview:imageSelected и fileUploadWithPreview:imageDelete, поэтому, если изображение удаляется после выбора, вы все равно можете применить правило 2:

$(document).ready(function() {

});

var toggle = function() {
  //console.log(upload.cachedFileArray.length);
  if (upload.cachedFileArray.length == 2) {
    $('input:submit').attr('disabled', false);
  } else {
    $('input:submit').attr('disabled', true);
  }
};

window.addEventListener('fileUploadWithPreview:imageSelected', function(e) {
  // optionally you could pass the length into the toggle function as a param
  // console.log(e.detail.cachedFileArray.length);
  toggle();
});

window.addEventListener('fileUploadWithPreview:imageDeleted', function(e) {
  // optionally you could pass the length into the toggle function as a param
  // console.log(e.detail.cachedFileArray.length);
  toggle();
});
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="https://unpkg.com/file-upload-with-preview@3.4.3/dist/file-upload-with-preview.min.css">
</head>

<body>
  <!-- Uploader -->
  <div class="custom-file-container" data-upload-id="myImage">
    <label>Upload your images <a href="javascript:void(0)" class="custom-file-container__image-clear" title="Clear Image">&times;</a></label>

    <label class="custom-file-container__custom-file">
      <form id="upload-form" action="{{url_for('upload')}}" method="POST" enctype="multipart/form-data">
      <input type="file" class="custom-file-container__custom-file__custom-file-input" accept="image/*" aria-label="Choose File" multiple>
      <input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
      <span class="custom-file-container__custom-file__custom-file-control"></span>
    </label>
    <div class="custom-file-container__image-preview"></div>
  </div>
  <input type="submit" name="send" disabled/>
  </div>
  <script src="https://unpkg.com/file-upload-with-preview@3.4.3/dist/file-upload-with-preview.min.js"></script>
  <script>
    var upload = new FileUploadWithPreview('myImage', {
      showDeleteButtonOnImages: true,
      text: {
        chooseFile: 'Nom del fitxer',
        browse: 'Examina'
      }
    });
  </script>
  <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
</body>

</html>
...