打赏
Fork me on GitHub

使用element中的el-upload获取本地文件并转为base64码实现预览

页面结构,其中有其他属性需要设置可前往element查看

<el-upload
     class="avatar-uploader"
      ref="upload"
      action="#"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleChange"
      :on-change="onChange"
      :auto-upload="false"
      :data="addList">
  <img v-if="imageUrl" :src="imageUrl" class="avatar" alt>
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

js代码,未定义的数据自行在data中定义

beforeUpload(){
  const isJPG = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
  this.$message.error('上传头像图片只能是 JPG 格式!');
  }
  if (!isLt2M) {
  this.$message.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
},
onChange(file,fileList){
  var _this = this;
      var event = event || window.event;
      var file = event.target.files[0];
      var reader = new FileReader(); 
      //转base64
      reader.onload = function(e) {
      _this.imageUrl = e.target.result //将图片路径赋值给src
      }
      reader.readAsDataURL(file);
},
handleChange(res, file) {
  this.imageUrl = URL.createObjectURL(file.raw);
},

css样式,摘自官方文档

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

 

posted @ 2020-06-16 23:02  l-coil  阅读(4581)  评论(0编辑  收藏  举报