vue+iview简单实现获取要上传文件的Base64字符串

代码:

<template>
  <div>
    <Upload
        :on-format-error="handleFormatError" :format="['jpg','jpeg','png']" ref="upload" :before-upload="handleUpload" action="">
      <Button icon="ios-cloud-upload-outline">选择上传文件</Button>
    </Upload>
    <div>选择上传文件:</div>
    <img :src="imgBase64" height="300" width="200"/>
  </div>
</template>
<script>
  export default {
    name: 'upload',
    data() { //
      return {
        uploadurl:'',
        imgBase64:'',
      }
    }, ////
    methods: {
      handleUpload(file) {//上传文件之前

        //读取文件的字符流
        const suffix = file.name.replace(/.+./, "");//取得文件的后缀名
        if(['jpg','JPG','jpeg','JPEG','png','PNG'].filter(x=>{return x==suffix}).length==0){
          console.log("文件格式错误");
          //清除文件
        }
        const reader = new FileReader();
        //将文件读取为 DataURL 以data:开头的字符串
        reader.readAsDataURL(file);
        reader.onload = e => {
            // 读取到的图片base64 数据编码 将此编码字符串传给后台即可
            const code = e.target.result;
            this.imgBase64=code;
            console.log("//////////////")
            console.log(code)
        }
        return false;
      },
      handleFormatError (file) {
        alert('格式错误')
          this.$Notice.warning({
              title: 'The file format is incorrect',
              desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
          });
      },
      upload() {//上传动作
        return false;
      },
    }
  } //
</script>
View Code

效果:

 <Upload>详细用法参考官网

原文地址:https://www.cnblogs.com/yanan7890/p/14441344.html