0

After uploading multiple images, I added image tag in html and then want to display selected images but I cannot display them well. How can I solve this problem?

<input type="file" id="inpFile" name="multi_image" multiple>
<button id="btnUpload">Upload File </button>
<div id="selectedFiles"></div>


<script type="text/javascript">
  const inpFile = document.getElementById("inpFile");
  const btnUpload = document.getElementById("btnUpload");
  var display = document.querySelector("#selectedFiles");

  btnUpload.addEventListener("click", function() {
    const formData = new FormData;

    for (const file of inpFile.files){
      formData.append("multi_image", file);
      img_tag = "<img src='images/"+ file.name + "'>"
      console.log(img_tag);
      display.innerHTML +=  img_tag+ "<br/>";
    }

    fetch('/project/create', {
        method: 'POST',
        body: formData
    })
    .then(response => {
      console.log(response);
    })
  })
</script>
Soo
  • 387
  • 2
  • 10
  • 19
  • 1
    Does this answer your question? [How to preview multiple images before upload?](https://stackoverflow.com/questions/39439760/how-to-preview-multiple-images-before-upload) – kmoser Jul 24 '20 at 02:27
  • So when you add an image in via a file input, it has access to the base64 which you can then use in the src attribute. I think you want to use [`FileReader.readAsDataURL()`](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL) – Bren Jul 24 '20 at 02:32

2 Answers2

0

Just change the img_tag as img_tag = "<img src='"+ URL.createObjectURL(file) + "'>"

Due to security risks JS won't give the path for our OS systems(Windows/Mac) directly inside the inpFile array.

Nav Kumar V
  • 320
  • 2
  • 10
0

This will help to solve your problem, it is completely based on the JS without using Jquery.

function previewImages() {

  var preview = document.querySelector('#preview');
  
  if (this.files) {
    [].forEach.call(this.files, readAndPreview);
  }

  function readAndPreview(file) {

    // File type validator based on the extension 
    if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
      return alert(file.name + " is not an image");
    }
    
    var reader = new FileReader();
    
    reader.addEventListener("load", function() {
      var image = new Image();
      image.height = 100;
      image.title = file.name;
      image.src = this.result;
      preview.appendChild(image);
    });
    
    reader.readAsDataURL(file);
    
  }

}

document.querySelector('#img-selector').addEventListener("change", previewImages);
<input id="img-selector" type="file" multiple>
<div id="preview"></div>
Hasitha Gamage
  • 107
  • 1
  • 4