function readImage (file) {функция не работает - PullRequest
0 голосов
/ 19 сентября 2019

У меня есть следующий скрипт, который должен проверять ширину и высоту выбранного файла изображения.Проблема, с которой я сталкиваюсь, заключается в том, что при запуске скрипта он не выполняет код внутри функции «function readImage (file) {», которая должна проверять размеры файла изображения, выполнять оператор if и отображать предупреждение.Может кто-нибудь увидеть, где я ошибся.

<input type='file' id="OverrideWayfinderBrowse" name="OverrideWayfinderBrowse" class="input-field" onChange="validateOverrideWayfinderBrowse(this);"/>

<div id="OverrideWayfinderPreview"><img class="OverrideWayfinderPreview"/></div>

function validateOverrideWayfinderBrowse(input){
  window.URL    = window.URL || window.webkitURL;
  var elBrowse  = document.getElementById("OverrideWayfinderBrowse"),
  elPreview = document.getElementById("OverrideWayfinderPreview"),
  useBlob   = false && window.URL; // `true` to use Blob instead of Data-URL
  console.log("OVERRIDE WAYFINDER IMAGE PREVIEW",elPreview);


  function readImage (file) {
    console.log("IMAGE READ");
    var reader = new FileReader();
    reader.addEventListener("load", function () {
      var image = new Image();
      image.addEventListener("load", function () {

        if(image.height >= 390) {
          console.log("OVERRIDE WAYFINDER IMAGE SIZE",image.height);
          var imageInfo = '<br /><br />Your selected image size is correct<br />  Display width ' +
          image.width + ',px <br /> Display height ' +
          image.height + 'px ' + '';
          elPreview.appendChild( this );
          elPreview.insertAdjacentHTML("beforeend",  imageInfo +'<br />');
        } else if(image.height <= 390) {
          console.log("ELSE");
          $.alert({
            type: 'red',
            title: 'Image select error!',
            content: 'The wayfinder image you have seleted is incorrect, ' + image.width + ' by ' + image.height + '.<br/><br/> Please resize your image to a miniumn height of 390px.<br/><br/>Resizing upwards reduces the quality of the image. Start with a large image and resize downwards.<br/><br/>For help read section 1.5 in the knowledgebase',
            icon: 'fa fa-rocket',
            animation: 'zoom',
            boxWidth: '50%',
            closeAnimation: 'zoom',
            buttons: {
              okay: {
                text: 'Try again',
                btnClass: 'btn-blue'
              }
            }
         });
        }
      });

      image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
      if (useBlob) {
        window.URL.revokeObjectURL(file);
      }
    });
    reader.readAsDataURL(file);
    }
    elBrowse.addEventListener("change", function() {
      var files  = this.files;
        var errors = "";
        if (!files) {
          errors += "File upload not supported by your browser.";
        }
        if (files && files[0]) {
          for(var i=0; i<files.length; i++) {
          var file = files[i];
          if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
            readImage( file );
          } else {
            errors += file.name +" Unsupported Image extension\n";
          }
        }
      }
      if (errors) {
        alert(errors);
      }
  });
};

Большое спасибо заранее за вашу помощь и время.

1 Ответ

1 голос
/ 19 сентября 2019

Как уже упоминалось @Lennholm, вы неправильно связываете событие изменения.

  1. Вы связываете событие изменения непосредственно с элементом здесь onChange="validateOverrideWayfinderBrowse(this);"

, но вытакже добавили слушатель события изменения в функцию, которая никогда не будет работать, потому что событие уже произошло elBrowse.addEventListener("change", function() {};

Вы также передаете элемент ввода в функцию и никогда не используете его.

Что вам нужно сделать, это переместить код изнутри прослушивателя вложенных событий и поместить его непосредственно в вашу функцию, покачтение файла из входного параметра.Попробуйте.

function validateOverrideWayfinderBrowse(input) {
  window.URL = window.URL || window.webkitURL;
  elPreview = document.getElementById("OverrideWayfinderPreview");
  useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
  console.log("OVERRIDE WAYFINDER IMAGE PREVIEW", elPreview);

  function readImage(file) {
    console.log("IMAGE READ");
    var reader = new FileReader();
    reader.addEventListener("load", function() {
      var image = new Image();
      image.addEventListener("load", function() {

        if (image.height >= 390) {
          console.log("OVERRIDE WAYFINDER IMAGE SIZE", image.height);
          var imageInfo = '<br /><br />Your selected image size is correct<br />  Display width ' +
            image.width + ',px <br /> Display height ' +
            image.height + 'px ' + '';
          elPreview.appendChild(this);
          elPreview.insertAdjacentHTML("beforeend", imageInfo + '<br />');
        } else if (image.height <= 390) {
          console.log("ELSE");
          $.alert({
            type: 'red',
            title: 'Image select error!',
            content: 'The wayfinder image you have seleted is incorrect, ' + image.width + ' by ' + image.height + '.<br/><br/> Please resize your image to a miniumn height of 390px.<br/><br/>Resizing upwards reduces the quality of the image. Start with a large image and resize downwards.<br/><br/>For help read section 1.5 in the knowledgebase',
            icon: 'fa fa-rocket',
            animation: 'zoom',
            boxWidth: '50%',
            closeAnimation: 'zoom',
            buttons: {
              okay: {
                text: 'Try again',
                btnClass: 'btn-blue'
              }
            }
          });
        }
      });

      image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
      if (useBlob) {
        window.URL.revokeObjectURL(file);
      }
    });
    reader.readAsDataURL(file);
  }
  
  // use the input element you passed instead of "this" here
  var files = input.files;
    var errors = "";
    if (!files) {
      errors += "File upload not supported by your browser.";
    }
    if (files && files[0]) {
      for (var i = 0; i < files.length; i++) {
        var file = files[i];
        if ((/\.(png|jpeg|jpg|gif)$/i).test(file.name)) {
          readImage(file);
        } else {
          errors += file.name + " Unsupported Image extension\n";
        }
      }
    }
    if (errors) {
      alert(errors);
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.css">

<input type='file' id="OverrideWayfinderBrowse" name="OverrideWayfinderBrowse" class="input-field" onChange="validateOverrideWayfinderBrowse(this);" />

<div id="OverrideWayfinderPreview"><img class="OverrideWayfinderPreview" /></div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...