废话不多说上代码

//图片与Base64编码字符串 互转
<template>
  <div>
    <input
      type="file"
      id="id"
      name="image"
      @change="shangc($event)"
      accept="image/jpg, image/jpeg, image/png"
    />
    <br/>
    // 这里写转入的图片
    <img :src="picPath" alt="">  
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: "",
      picPath:''
    };
  },
  methods: {
    shangc(e) {
      let files = document.getElementById("id").files[0];
      //转码base64
      let reader = new FileReader();
      let imgFile;
      reader.readAsDataURL(files);
      reader.onload =  e => {
        imgFile = e.target.result;
        let arr = imgFile.split(",");
        // arr[1] 就是图片的 Base64编码字符串
        console.log(arr[1]); 
        
     	//这里的 picPath 'data:image/png;base64,'+ base64为编码字符串拼接形成图片的
        this.picPath='data:image/png;base64,'+arr[1]
        
      };
    }
  }
};
</script>

<style  scoped>
img{
  width: 400px;
    height: 400px;
    border: 1px solid red;
}
</style>
Logo

前往低代码交流专区

更多推荐