Javascript image upload and display

后端 未结 2 468
渐次进展
渐次进展 2021-01-05 17:13

My basic task is select image and display it,without saving it in database.

For this

1.I have made a select tag in html,through which I can upload the image

相关标签:
2条回答
  • 2021-01-05 17:36

    You may want to checkout this solution (where my code derives from). It involves a little bit of jQuery but if you truly must write it out in pure JS, here you go.

    Note: I modified your tags to conform to the JS below. Also try to stay away from writing any inline scripts. Always good to keep your HTML and JS loosely coupled.

    var fileTag = document.getElementById("filetag"),
        preview = document.getElementById("preview");
        
    fileTag.addEventListener("change", function() {
      changeImage(this);
    });
    
    function changeImage(input) {
      var reader;
    
      if (input.files && input.files[0]) {
        reader = new FileReader();
    
        reader.onload = function(e) {
          preview.setAttribute('src', e.target.result);
        }
    
        reader.readAsDataURL(input.files[0]);
      }
    }
    <input type="file" id="filetag">
    <img src="" id="preview">

    0 讨论(0)
  • 2021-01-05 18:03

    You can also use the Image() constructor. It creates a new HTML Image Element.

    Example -

    document.getElementById("filetag").addEventListener("change", function(e) {
    
      let newImg = new Image(width, height);
    
      // Equivalent to above -> let newImg = document.createElement("img");
    
      newImg.src = e.target.files[0];
      newImg.src = URL.createObjectURL(e.target.files[0]);
    
      output.appendChild(newImg);
    });
    

    Reference - https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image

    0 讨论(0)
提交回复
热议问题