'How can i display an image taken from file input?

I am new to web development and i am working on a project and wanted to be able to take an image as a file input, and then, on button press, to 'send' the image chosen, which is just displaying it. I have worked with a text input before, but i have no ideea how to handle file inputs. I searched and found another stackoverflow post that worked, but only for one image, so i tried to change it but didn't manage to accomplish anything. This was the code the response got (i am sorry to the person who gave this response, i can't find the post).

var reader = new FileReader();
reader.onload = function (e) {
    $('#blah').attr('src', e.target.result);
}
   
   function readURL(input) {
        if (input.files && input.files[0]) {
            reader.readAsDataURL(input.files[0]);
        }
    }
    
    $("#imgInp").change(function(){
        readURL(this);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

About the only thing i did was to convert the jQuery to vanilla JS, as what i tried other than that has failed miserably. Edit: this was about what i got:

let container = document.getElementById("messages");
let inp = document.getElementById("file");

let reader = new FileReader();
reader.onload = function (e) {
    container.innerHTML += `<img src="${e.target.result}" class="imgs">`;
}
   
function readURL(input) {
  if (input.files && input.files[0]) {
  // note: here i also tried to use a for loop in case there were multiple images, it didn't work
    reader.readAsDataURL(input.files[0]);
  }
}

inp.addEventListener("change", function(){
  readURL(this);
});
/* some CSS to make it look better */

#btn {
  background: black;
  color: white;
  width: 50px;
  height: 50px;
  margin-bottom: 10px;
  font-size: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.imgs {
  max-height: 200px;
}

#file {
  transform: translateX(-999999999px);
  transform: translateY(-999999999px);
}
<div id="interact">
  <div id="btn" onclick="document.getElementById('file').click()"> + </div>
</div>

<div id="messages">
  
</div>
<input type='file' multiple accept="image/*" id="file"/>

Note: i believe it was a syntax/naming mistake on my part; now it partially works, though it still cannot read multiple images at once.

I was hoping someone better versed into web development could help me out. Thank you in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source