Home > Software design >  I'm trying to upload and display images that the user selected in JavaScript
I'm trying to upload and display images that the user selected in JavaScript

Time:11-21

I'm trying to upload and display images that the user selected by using the id element in HTML; e.g.

HTML:

<span id="propicout"><img src="#" alt="PROFILE" id="propicout"></span>

JAVASCRIPT:

const propic = document.getElementById("propicin").value;

Now I just need to set the id, "propicout" to the image the user uploaded.

I tried some YouTube tutorials, some were complicated, and some didn't work. I also looked at stack-overflow but they didn't really match what I was doing.

CodePudding user response:

The code you're looking for is URL.createObjectURL().

This creates a temporary URL pointed to the image data in-memory (or cached on disk) that you can use like any other URL. You assign that to the src attribute on your image element, and you're good to go.

document.querySelector('input[type="file"]').addEventListener('change', (e) => {
  document.querySelector('img').src = URL.createObjectURL(e.currentTarget.files[0])
});

JSFiddle: https://jsfiddle.net/qg1j8e25/1/

(Also, by the way... you're re-using an ID in your HTML. Don't do that. IDs should only be used once.)

  • Related