title: JS Multiple image upload width validation
body: <p>I have a multiple file upload field for images that I want to validate each image's width before upload to ensure it's less than 640px.</p>
  
  <p>If one of the images is larger, preferably I would have it removed from the FileList before the rest of the images are uploaded. Reading a bit around tells me this is not possible because FileList is read only? (Possible workaround would be to make a separate array, but I'm using Rails with gem s3_direct_upload which builds upon jquery-fileupload, so I'm not entirely sure how to go about doing that).</p>
  
  <p>Therefore at least I would like to clear the FileList and alert the user so that he can select all the images another time without the images that were too large.</p>
  
  <p>My problem is that I'm looping through all the images getting the width with FileReader and image.onload (which is async?), and since the invalid image(s) could be anywhere in the loop, I haven't been able to figure out a proper way to flag one or more of the images as invalid, wait for the loop to finish completely before handling the result. Setting 'validated' after the image has been loaded and the width is known does not seem to work since it's async hence the method always returns true.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>$('#fileUploadField').change(function (e) {
    if (window.FileReader) {
      if (this.files &amp;&amp; this.files[0]) {
        var images = this.files;
        if(images &amp;&amp; images[0]) {
          for (var i=0 ; i &lt; images.length; i++) {
            var validated = validateImg(images[i]);
            if (validated = false) {
             //...do something
            }
          } 
        }
      }
    }
  });
  
  function validateImg(file) {
    var reader = new FileReader(),
        image = new Image(),
        validated = true;
  
    reader.readAsDataURL(file);
  
    image.src = _file.target.result;
    reader.onload = function(_file) {
      image.onload = function() {
          var w = this.width,
              n = file.name;
        if (w &gt; 640) {
          validated = false;
        } else {
          $('.imgs-preview-wrap').append('&lt;img src="'+ image.src +'"&gt;');
        }
      };
    };
    return validated;
  }
  </code></pre>