在vue 中使用input type=file 获取上传图片,并转为base64码放在img 的src中,实现预览效果

<!--页面部分-->
<template>
  <div class="hello">
    <p class="title">{
    
    {
    
     action }}</p>    
    <p class="selectfile">请选择预览图片</p>
    <input class="select" ref="imgInput" type="file" accept="image/*" @change="uploadImg($event)">
 
    <ul v-show="isUpload">
        <p class="green" v-if="imgUrl.length!==0">图片预览</p>
        <li v-for="(list,index) in imgUrl" :key="list">
            <img ref="imgimg" :src="list.url" alt="">
            <button class="remove" @click="remove(index)">删除</button>
        </li>
    </ul>
  </div>
</template>
<!--js部分-->
<script>
export default {
    
    
  name: 'Home',
  data () {
    
    
    return {
    
    
      action: 'Welcome to my album !',
      isUpload:false,
      imgUrl:[],
    }
  },
  methods: {
    
    
    uploadImg(e){
    
    
      console.log(e.target.files);
      this.isUpload=true;
      let file=e.target.files[0];
      let url='';
      var reader = new FileReader();
      reader.readAsDataURL(file);
      let that=this;
      reader.onload = function (e) {
    
    
        url=this.result.substring(this.result.indexOf(',')+1);
        // that.imgUrl='data:image/png;base64,'+url
        // that.$refs['imgimg'].setAttribute('src','data:image/png;base64,'+url);
        that.imgUrl.push({
    
    
          id:that.imgUrl.length+1,
          url:'data:image/png;base64,'+url
          })
      }
    },
    remove(index){
    
    
       this.imgUrl.splice(index,1)
    }
  },
}
</script>
<!--样式部分-->
<style scoped>
.green{
    
    
  color: #42b983
}
ul {
    
    
  list-style-type: none;
  padding: 0;
}
img{
    
    
  width: 400px;
}
.title{
    
    
  font-size: 40px;
  background: linear-gradient(to right, red, blue);
  -webkit-background-clip: text;
  color: transparent;
  font-weight: 800
}
.remove{
    
    
  position: relative;
  bottom: 120px;
  left: 70px;
  border-radius: 4px;
  background-color: darkred;
  border: 1px solid gray;
  color: white;
  width: 50px;
  height: 25px;
  text-align: center
}
.select{
    
      
  opacity:0;
  z-index: 111;
  position: relative;
  top: -50px;
  left: 0%;
  height: 50px;
  width: 163px;
}
.selectfile{
    
    
  color: white;
  padding: 10px 20px;
  width: 120px;
  background-color: #4180d6;
  z-index: 1;
  margin: 0 auto;
  border-radius: 4px;
}
</style>

效果展示图

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_39380337/article/details/102915530