input file上传图片转成base64

效果图


上传图片.jpg

html

 

上传logo

js

data() {
    return {
      addedPreviewFile:'',
    }
  },
  computed: {
    preview() {
      return this.addedPreviewFile
    },
    accept() {
      return 'png'
    }
  },
  methods: {
    deleteImg() {
      this.addedPreviewFile = ''
    },
    addImg() {
      let inputDOM = this.$refs.inputer
      let file = inputDOM.files[0]
      if (!file) return
      let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1).toLowerCase();
      let fileSize = file.size;
      let isImage = false;
      for (let mimeType of this.accept.split(',')) {
        if (mimeType === testmsg) {
          isImage = true;
          break
        }
      }
      if (!isImage) {
        this.$message.error('上传图片必须是PNG格式!');
        return false;
      }
      if (fileSize > 1024 * 1024) {
        this.$message.error('上传图片大小不能超过1MB!');
        return false;
      }
      let re = new FileReader()
      re.readAsDataURL(file)
      let that = this
      re.onload = function (re) {
        that.addedPreviewFile =  re.target.result
      }
    },
  }

css

.g-c-eff{color: #409eff;}
.img-box{
  width: 82px;
  height: 82px;
  background-color: #fcfeff;
  border:dashed 1px #409eff;
  margin-right: 20px;
  position: relative;
}
.file-input{
  width: 80px;
  height: 80px;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  cursor: pointer;
}
#pro-pic{
  max-width: 80px;
  height: 80px;
  display: block;
  object-fit: scale-down;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
}
.deleteIcon {
  position: absolute;
  top: -13px;
  right: -11px;
  display: block;
  background-color: #000000;
  opacity: 0.8;
  text-align: center;
  width: 24px;
  height: 24px;
  line-height: 24px;
  border-radius: 50%;
  cursor: pointer;
}

你可能感兴趣的:(input file上传图片转成base64)