Home > Mobile >  how to fill a div with an image the user uploads?
how to fill a div with an image the user uploads?

Time:03-25

I am working on a rudimentary site that enables users to upload images to the server and download them from it. I want to add a "preview" feature that will allow the user to see its photo beforehand. Here is my code:

 <div >
        <input type="file"  id="picker"/>
        <img src= this.input alt="IDK why, but I can't display that." >;

CodePudding user response:

You can use JavaScript to dynamically update the image source of the img tag.

const img = document.getElementById('preview');
const input = document.getElementById('picker');
input.onchange = function(ev) {
  const file = ev.target.files[0]; // get the file
  const blobURL = URL.createObjectURL(file);
  img.src = blobURL;
}
<div >
  <input type="file"  id="picker" />
  <img id="preview" alt="IDK why, but I can't display that."  width="200">
</div>

CodePudding user response:

I updated the code.

const selectFile = evt => {
  const [file] = evt.target.files;
  if (file) {
    document.getElementById('preview').src = URL.createObjectURL(file);
  }
}
<div >
  <input type="file"  id="picker" onchange="selectFile(event)" />
  <img id="preview" alt="IDK why, but I can't display that." >;
</div>

  • Related