element-ui中el-upload上传图片本地预览功能

2,586 阅读1分钟
<el-upload
  class="avatar-uploader"
  action="https://jsonplaceholder.typicode.com/posts/"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload"
:on-change="handleChange"
>  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

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

<script>
  export default {
    data() {
      return {
        imageUrl: ''
      };
    },
    methods: {
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        // 判断图片大小和格式
        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;
      },
// 上传change事件 handleChange(file, fileList) {      this.localFile = file.raw // 或者 this.localFile=file.raw      // 转换操作可以不放到这个函数里面,      // 因为这个函数会被多次触发,上传时触发,上传成功也触发      const reader = new FileReader()      reader.readAsDataURL(this.localFile)// 这里也可以直接写参数event.raw      // 转换成功后的操作,reader.result即为转换后的DataURL ,      // 它不需要自己定义,你可以console.log(reader.result)看一下      reader.onload = () => {        console.log(reader.result)      }      /* 另外一种本地预览方法 */      const URL = window.URL || window.webkitURL      this.imageUrl = URL.createObjectURL(file.raw)      console.log('imageUrl', this.imageUrl)      // 转换后的地址为 blob:http://xxx/7bf54338-74bb-47b9-9a7f-7a7093c716b5    },    }
  }
</script>