在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>

效果展示图

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值