Multiple Upload Thumbnail

Asked

Viewed 35 times

2

I have a field to upload PDF documents, when attaching a document appears the PDF icon, but I am using multiple upload and only an icon appears when ideally it would appear an icon for each attached file, I know it’s possible but I don’t have much knowledge of Js, someone could help?

Code: HTML

  <label id="timg" for="upload-photo">Upload <i class="fa fa-folder-open" aria-
    hidden="true"></i></label> 
<input type="file" multiple id="upload-photo" required accept=".pdf, application/pdf">

<div id="thumbs"> 
<img src="" id="pdfimg" style="display: block; width: 50px; height: 50px;"/> </div>

JS

const icons = {

'application/pdf': 'http://iconbug.com/data/5b/507/52ff0e80b07d28b590bbc4b30befde52.png',

}

const input = document.querySelector('#upload-photo');
const image = document.querySelector('#pdfimg');         //Script PDF MultipleUpload
input.addEventListener('change', function() {
const tipo = this.files[0].type;
image.src = icons[tipo];

});

1 answer

2


You have to declare all icons in the object icons, in the example below I added an icon to represent the image of a file of type image/png. Whenever there’s change in input an image is created for the file that was sent, based on its type.

const icons = {
  'application/pdf':'http://iconbug.com/data/5b/507/52ff0e80b07d28b590bbc4b30befde52.png',
  'image/png': 'http://findicons.com/files/icons/1637/file_icons_vs_2/256/png.png'
}

const input = document.querySelector('#upload-photo');
const thumbs = document.querySelector('#thumbs');
input.addEventListener('change', function() {
  thumbs.innerHTML = "";
  for (var i = 0; i < this.files.length; i++) {
    var img = new Image();
    img.src = icons[this.files[i].type];
    img.className = "thumbImg";
    thumbs.appendChild(img);
    var span = document.createElement('span');
    span.innerHTML = this.files[i].name;
    thumbs.appendChild(span);
  }
});
.thumbImg {
  width: 50px;
  height: 50px;
}
<label id="timg" for="upload-photo">Upload <i class="fa fa-folder-open" aria-
    hidden="true"></i></label>
<input type="file" multiple id="upload-photo" required accept=".pdf, application/pdf">

<div id="thumbs">
</div>

  • Thank you very much friend, everything worked out, only one more question is possible to show the name of the file under the image, when attached?

  • 1

    @Henriquebretone Yes, I edited the answer, I added a span with the name (this.files[i].name) right after the image =)

  • 1

    Thanks even guy saved my serious life.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.