vue預覽本地圖片


<template>
  <div>
    <a href="javascript:void(0);" @change="addImage" class="a">
      <input type="file" class="fileopen" />上傳圖片
    </a>
    <img :src="imgsrc" alt class="imgview" accept="image/png, image/jpeg, image/gif, image/jpg" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      imgsrc: ""
    };
  },
  methods: {
    addImage() {
      var input = document.querySelector("input");
      //1. 拿到fileinput里面的文件, 這個file是一個file對象, file對象不能直接展示的
      var file = input.files[0];

      //2. 讀取文件,成功img標簽可以直接使用的格式
      //FileReader類就是專門用來讀文件的
      var reader = new FileReader();
      window.console.log(file);

      //3. 開始讀文件
      //readAsDataURL: dataurl它的本質就是圖片的二進制數據, 進行base64加密后形成的一個字符串, 這個字符串可以直接作用img標簽的圖片資源使用

      reader.readAsDataURL(file);
      let _this = this;
      //4. 因為文件讀取是一個耗時操作, 所以它在回調函數中,才能夠拿到讀取的結果
      reader.onload = function() {
        window.console.log(reader.result);
        //直接使用讀取的結果
        _this.imgsrc = reader.result;
      };
      _this.imgsrc = file;
    }
  }
};
</script>

<style lang="less" scoped>
.imgview {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  border: 1px solid red;
}
.a {
  position: relative;
  display: block;
  text-decoration: none;
  color: aqua;
}
.fileopen {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  filter: alpha(opacity=0);
  width: 64px;
  overflow: hidden;
}
</style>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM