前段base64压缩图片upload上传

<template>
  
  <div class="base64-upload">
    <img src="../assets/addimg.png"  alt="" width="38" height="39">
    <input type="file"
           ref="uploadBtn"
           accept="image/jpeg,image/jpg,image/png,image/svg"
           @click="onClick"
           @change="onChange" />
  div>
template>

<script>
  import lrz from 'lrz'   //这里引用lrz 依赖 处理压缩
  import fastclick from 'fastclick'
  export default {
    data() {
      return {

      }
    },
    mounted(){

    },
    methods: {
      onClick(event){
        event.target.value = null        
        //避免上传图片后再次选择相同图片没效果,因为input file 的value 是相同的 不会触发change
      },
      onChange(event) {
        var _this=this;
        _this.$emit('start')
        if (event.target.files && event.target.files[0]) {
          let file = event.target.files[0]
          let reader = new FileReader()
          lrz(file,{width: 1920,quality :0.7})   
          // 这里的quality 是压缩百分比,但实际文件大小变成了10%左右

            .then(function (rst) {
              reader.addEventListener('load', e => {  
                let [, base64] = rst.base64.split(',')
                _this.$api.post('/****/oss/base64/uploadAndSave',{   //your imgupload url
                  img:base64,
                  fileName:file.name,
                  formId:0,
                  tabName:'yj_trademark_img'
                }).then(res=> {
                  var info = {
                    url: res.data.url,
                    pkidStr:res.data.pkidStr
                  }
                  _this.$emit('change', true,info)
                })
              })
              reader.readAsDataURL(file)
            })
            .catch(function (err) {
              _this.$emit('change', false,err)
            })
            .always(function (err) {
            });
        }
      }
    }
  }
script>

<style scoped>
  .base64-upload {
    position: relative;
    width:38px;
    height:39px;
    display: inline-block;
  }
  input {
    width: 38px;
    height: 39px;
    top: 0;
    left: 0;
    opacity: 0;
    position: absolute;
  }
style>

附上lrz 包的地址 及api
https://www.npmjs.com/package/lrz

你可能感兴趣的:(img,h5-app)