如何显示我输入的图像

时间:2020-09-14 08:32:58

标签: javascript image input display

我做了一个按钮,将图像作为输入,但是我找不到显示图片的方法。 我尝试制作一个空元素,然后像在其他网站上看到的那样更改其URL,但是没有用。

  • HTML

     <input 
         id="myImage"
         class="photo-upload"
         type="file"
         accept="image/*, image/jpeg">
    
         <img id="the-picture" width="200" />
    
  • JavaScripts

     const uploadPictureButton = document.querySelector(".photo-upload");
    
     uploadPictureButton.addEventListener("click", displayPicture);
    
     function displayPicture(event) {
         let image = document.getElementById("myImage");
         image.src = URL.createObjectURL(event.target.files[0]);
     };
    

3 个答案:

答案 0 :(得分:0)

代码中需要一些修复,必须读取文件并创建URL,这是代码的有效代码段。

const uploadPictureButton = document.querySelector(".photo-upload");

  uploadPictureButton.addEventListener('change', function () {
    displayPicture(this);
  });

 function displayPicture(input) {
    if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      document.getElementById('the-picture').setAttribute('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
  }
 }
 <input 
     id="myImage"
     class="photo-upload"
     type="file"
     accept="image/*, image/jpeg">

<img id="the-picture" width="200" /> 

答案 1 :(得分:0)

您也可以使用innerHTML显示图像。

答案 2 :(得分:0)

尝试一下,它对我有用

<img height="100" width="100" alt="avatar" id="imgPreview> <input type="file" onchange="document.querySelector("#imgPreview").src = window.URL.createObjectURL(this.files[0])">

相关问题