0

I'm creating a social media application. I got the image input from the user, but I was stuck in displaying the image.

Here is my HTML file

<form id="form">
   <div id="closeForm"><i class="fas fa-window-close"></i></div>
   <label>
     <p>Enter the title:</p>
     <input id="newTitle" placeholder="Art Title" type="text">
   </label>
   <label>
     <p>Select your image:</p>
     <input id="newImg" class="imgInput" accept="image/*" type="file">
   </label>
   <input id = "formBtn" type="button" acc value="Upload">
</form>

This is my JS file

document.getElementById('formBtn').onclick=()=>{
    let newTitle = document.getElementById('newTitle').value;
    let newImg =  document.getElementById('newImg').value;

    let fragment = `
       <img class="art_img" src="${newImg}" alt="" srcset="">
       <p id="title">${newTitle}</p>`;

artContainer.innerHTML+=fragment;
}
  • 1
    what is artContainer in here? – Ghost Ops Oct 07 '21 at 07:42
  • 1
    You need https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL, see here: https://jsfiddle.net/Lu0ga1v2/ –  Oct 07 '21 at 07:44
  • 1
    Duplicate: [Preview an image before it is uploaded](https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded) –  Oct 07 '21 at 07:44
  • artContainer is a place where I display the image, I didn't shown the html for that here, –  Oct 07 '21 at 07:51

1 Answers1

0

Use the FileReader object to create a blob and attach it to the element.

Example:

        const reader = new FileReader();
        reader.onload = (e) => {
                imgElm.src = e.target.result;
        };
        // do some checks to make sure its not empty
        reader.readAsDataURL(input.files[0]);
MrCeRaYA
  • 581
  • 4
  • 6