0

To upload multiple files and create thumbnails I'm using code:

<form class="article-comments__form">
  <textarea class="article-comments__textarea" placeholder="Join the discussion…"></textarea>
  <div class='article-comments__comment-section--footer'>
    <div class="article-comments__uploadedFiles"></div>
    <button class="article-comments__upload-image">
      <input class="imgUploadInput" type="file" name="imgfile" accept="image/*" multiple />
     </button>
     <span class="article-comments__upload--description">Add Images</span>
              
     <button class="article-comments__postButton disabled" type="submit" aria-label="Post">Post</button>
   </div>
 </form>



imgUploadInput.onchange = (e) => {
  const files = e.target.files;
  const output = imgUploadInput.parentNode.querySelector('.article-comments__uploadedFiles');
// create and add thumbnails to Uploaded Files Block
  for (let i = 0; i < files.length; i++) {
    if (!files[i].type.match("image")) continue;
      const picReader = new FileReader();
      picReader.addEventListener("load", function (event) {
      const picFile = event.target;
      const div = document.createElement("div");
      div.classList.add('image')
      div.innerHTML = `<img class="article-comments__thumbnail" src="${picFile.result}"/>`;
      output.appendChild(div);
    });
    picReader.readAsDataURL(files[i]);
  }
}

The code above is working perfectly if I select multiple files at once. What I need is to upload multiple images adding an image one at a time, is there a way to do that with html & JavaScript? Each time I try to upload another image the old one is deleted from input(file type) and I get to submit just la last added image.

Could someone please provide some resources or a code snippet? The code above is displaying the thumbnail but the input is not keeping the previous loaded images.

Alina
  • 45
  • 4

1 Answers1

0

this might not be what you want/need but to improve what you already got then i would, 1) remove the check of image type (as you already have a filter attribute on the file input. 2) use Blob Object URLs instead of encoding and decoding to/from base64 (which is wasteful)

just do:

imgUploadInput.onchange = evt => {
  const output = imgUploadInput.parentNode.querySelector('.article-comments__uploadedFiles')
  // create and add thumbnails to Uploaded Files Block
  const previews = [...evt.target.files].map(file => {
    const div = document.createElement('div')
    div.append(Object.assign(new Image(), { 
      src: URL.createObjectURL(file),
      alt: file.name,
      className: 'article-comments__uploadedFile' 
    }))
    div.classList.add('image')
    return div
  }
  output.append(...previews);
}
Endless
  • 34,080
  • 13
  • 108
  • 131