Friday, 25 December 2020

FileList, push new image files, access/remove by index

This input element allows to take multiple images, for example if i select 2 images i get: FileList {0: File, 1: File, length: 2}. Then if i select again for example 1 image i get another FileList: FileList {0: File, length: 1}. There's a chance to push this new image to the first FileList created before? And it's possible to remove an image of the FileList by his index? Thanks in advance.

function handleFileSelect(evt) {
      var files = evt.target.files; // FileList object
      console.log(files);

      for (var i = 0; i < files.length; i++) {          
        console.log(files[i]);
      }
      // Loop through the FileList and render image files as thumbnails.
      for (var i = 0, f; f = files[i]; i++) {
        if (!f.type.match('image.*')) {
          continue;
        }

      let reader = new FileReader();
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
.thumb {
      height: 75px;
      border: 1px solid #000;
      margin: 10px 5px 0 0;
    }
<input type="file" id="files" name="files[]" multiple />
  <output id="list"></output>

enter image description here



from FileList, push new image files, access/remove by index

No comments:

Post a Comment