js圖片上傳預覽

weixin_33982670發表於2018-03-15
<div class="col-sm-6">
  <img id="headPortraitImgShow" src="" alt=""  />
  <input type="file" id="headPortraitUpload" style="margin-top:10px;">
</div>
<script src="jquery-3.3.1.min.js"></script>
<script>
$("#headPortraitUpload").on("change",headPortraitListener);


 /*定義全域性變數存貯圖片資訊*/
 var base64head="";
/*頭像上傳監聽*/
function headPortraitListener(e) {
    var img = document.getElementById('headPortraitImgShow');
      if(window.FileReader) {
          var file  = e.target.files[0];
          var reader = new FileReader();
          if (file && file.type.match('image.*')) {
              reader.readAsDataURL(file);
          } else {
              img.css('display', 'none');
              img.attr('src', '');
          }
          reader.onloadend = function (e) {
          img.setAttribute('src', reader.result);
          base64head = reader.result;
        }
      }
}

</script>

  

相關文章