SoFunction
Updated on 2025-04-05

vue element upload to realize local image preview

vue uses element to implement local preview. The most important thing is to convert the image path to base64 for your reference. The specific content is as follows

HTML

<el-upload
 class="avatar-uploader"
 action="123" //This path is not important, you can write it casually :show-file-list="false"
 :on-success="handleAvatarSuccess"
 :on-change="onchange"
 :before-upload="beforeAvatarUpload">
 <img v-if="imageUrl" :src="imageUrl" class="avatar">
 <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

js part

<script>
 export default {
  data() {
   return {
    imageUrl: '',
   };
  },
  methods: {
   handleAvatarSuccess(res, file) {
     = ();
   },
   beforeAvatarUpload(file) {
    const isJPG =  === 'image/jpeg';
    const isLt2M =  / 1024 / 1024 < 2;

    if (!isJPG) {
     this.$('Uploading avatar images can only be in JPG format!');
    }
    if (!isLt2M) {
     this.$('The uploaded avatar image size cannot exceed 2MB!');
    }
    return isJPG && isLt2M;
   },
   //After uploading the image, call the onchange method to obtain the local path of the image   onchange(file,fileList){
     var _this = this;
        var event = event || ;
        var file = [0];
        var reader = new FileReader(); 
        //Turn base64         = function(e) {
         _this.imageUrl =  // Assign the image path to src        }
        (file);
   }
  }
 }
</script>

You can now realize local preview of the picture.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.