Javascript image upload and display

后端 未结 2 469
渐次进展
渐次进展 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]);
      }
    }
    
    

提交回复
热议问题