Package component El upload: upload a single picture through v-model

The El upload image in the element UI has been encapsulated twice. (by default, everyone has a certain vue foundation, and there are only a few details.)

In the project, we mainly get pictures or other parameters. Here is the Guid returned after uploading

So I have concentrated on the upload actions, such as the input v-model to get the parameters directly

Page display code:

<imgeFile v-model="form.license" allclass="passport-uploader"
                  inclass="passport-uploader-icon passport-s3" onclass="passport passport-pic">
                     <div class="el-upload__tip" slot="tip">Please upload 300*420 No more than 500 pixels K Size picture,Picture format support.PNG or.JPG</div>
   </imgeFile>

effect:

 

Component code:

<template>
  <el-upload :class="allclass" :accept="accept" :action="fileUrl" :show-file-list="false"
    :on-success="handlePassportSuccess" :before-upload="beforePassportUpload">
    <!---Display effect after uploading pictures  imge It's packaged imageUrl yes Guid Unified processing--->
    <imge v-if="imageUrl"   :src="imageUrl" :class="onclass"/>
   <!---Display effect before uploading pictures--->
    <i v-else :class="inclass"></i>
      <!---Tips--->
     <slot name="tip" slot="tip"></slot>
  </el-upload>
</template>

<script>

  import {  Url,  CCONFIG} from "@/api/apiconfig";//Upload image address
  import {getFileUrl} from "@/api/upload"; //How to get pictures
  export default {
      model:{
      prop:"value",
  },
    props: {
     //coordination v-model Load initial
       value: {
        type: String,
        default: ""
       },
       //How many megabytes will compression begin
       sizeKB:{
        type:Number,
        default: 100
       },
       //How many megabytes is the maximum
       maxSizeM:{
        type:Number,
        default: 5
       },
       //Year on year compression ratio of pictures
       scale:{
        type:Number,
        default: 0.3
       },
      //Upload file type
      accept:{
        type: String,
        default: "image/jpeg,image/png"
      },

      //Overall style
      allclass: {
        type: String,
        default: "passport-uploader-logo"
      },
      //Style before clicking
      inclass: {
        type: String,
        default: "el-icon-plus avatar-uploader-icon"
      },
      //Style after clicking
      onclass: {
        type: String,
        default: "passport-logo"
      },

    },
    data() {
      return {
        fileUrl: Url.imge_Upload,//Upload server address
        imageUrl: "",
        filelist:[],
      };
    },
    computed: {},
    created: function () {
         this.imageUrl=this.value
    },
     mounted() {
     },
    methods: {
      //Upload success return value
      handlePassportSuccess(res, file) {
        if (res.code == "0000") {
            this.imageUrl=res.data.id;
          //return v-model Parameters of (key)
          this.$emit('input', res.data.id) 
        } else
          this.imageUrl = "";
      },

    //The code below the compressed image is the compressed file size 
   beforePassportUpload(file) {
      var that = this;
      return new Promise((resolve, reject) => {
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const  kb= file.size/ 1024;
        const sizeM= file.size/ 1024/1024;
        const isLtKB = kb  < this.sizeKB;
        let bool = false;
        let msg = "";
        if ((isJPG || isPNG)&&sizeM<=this.maxSizeM) {//Determine whether the format requirements are met
          bool = true;
        } 
        else 
        if(sizeM>this.maxSizeM){
           var mag="Upload file must be less than"+this.maxSizeM+"M";
            this.$message({message:mag,type:'error',offset:10 });
            reject(file);
        } else 
        {
          this.$message({message:"Upload file must be jpg,png format!",type:'error',offset:10 });
           reject(file);
        }
        if (bool && !isLtKB) {//If the format is satisfactory, but size Too large, process image
          let image = new Image(),
          resultBlob = "";
          image.src = URL.createObjectURL(file);
          image.onload = () => {
            resultBlob = that.compressUpload(image);//Blob
            resolve(resultBlob);
          };
        } else if (bool && isLtKB) {
          resolve(file);//file
        }
      });
    },
    compressUpload(image) {
      let canvas = document.createElement("canvas");//Create canvas elements
      let ctx = canvas.getContext("2d");
      let initSize = image.src.length;
      let { width } = image,
          { height } = image;
      canvas.width = width;
      canvas.height = height;
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(image, 0, 0, width, height);
      let compressData = canvas.toDataURL("image/jpeg", this.scale); //Proportional compression
      let blobImg = this.dataURItoBlob(compressData);//base64 turn Blob
      return blobImg;
    },
    dataURItoBlob(data) {
      let byteString;
      if (data.split(",")[0].indexOf("base64") >= 0) {
        byteString = atob(data.split(",")[1]);//Binary conversion
      } else {
        byteString = unescape(data.split(",")[1]);
      }
      let mimeString = data
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
      let ia = new Uint8Array(byteString.length);
      for (let i = 0; i < byteString.length; i += 1) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ia], { type: mimeString });
    },
   
   
   },
  
  };
</script>

Tags: Vue less

Posted on Sat, 16 May 2020 10:09:45 -0400 by Dr Evil