vue移动端基于vant的uploader封装组件和上传图片压缩

vue移动端基于vant的uploader封装组件和上传图片压缩

代码如下:

<template>
  <div class="upload_content">
      <van-cell title="照片" :border="false" title-class="upload_title">
      </van-cell>
      <!-- 支持附件格式:pdf/ppt/word/excel/jpg -->
      <div style="display: flex;flex-direction: column;">
        <span style="margin-left: 15px;color: #606266;font-size: 12px;">支持扩展名:jpg、jpeg、webp、png,文件不超过10M</span>
        <van-uploader
        accept=".pdf,.ppt,.word,.excel,.jpg,.png,.jpeg"
        v-model="newFileList"  :max-count="maxCount" :max-size="10 * 1024 * 1024 "  @oversize="onOversize" :after-read="afterRead" style="margin-left: 15px;margin-top: 10px;" upload-icon="plus" upload-text="上传照片"/>
      </div>

</div>
</template>

<script>
import { Toast } from 'vant';
//引入
import {commonPhotoCompress} from '@/utils'
export default {
name:'imageUpload',
props:{
  fileList:{
    default:()=>[],
    type:Array
  },
  maxCount:{
    default:1,
    type:Number
  },
  objTable:{
    default:'',
    type:String
  },
  fileType:{
    default:'',
    type:String
  }
},
data(){
  return{
    profilePhoto:'',
    newFileList:this.fileList
  }
},
methods:{
  onOversize(file) {
    console.log(file);
    Toast('文件大小不能超过 10M');
  },
  async afterRead(oldFile){
    console.log('111',oldFile.file.size)
    oldFile.status='uploading',
    oldFile.message='上传中...'
    this.$emit('uploadFileId','')
    commonPhotoCompress(oldFile.file, async file => {
      console.log('222',file.size)
      const formData = new FormData();
      formData.append('file', file); // 假设你的文件在 data 对象的 file 属性中
      formData.append('objTable',this.objTable); // 假设你的文件在 data 对象的 file 属性中
      formData.append('fileType', this.fileType); // 假设你的文件在 data 对象的 file 属性中

    this.$apiData.fileUpload(formData).then(res=>{
      console.log('666',res)
      if(res && res.data.code =='0000'){
          let data = res.data.data
          console.log('data',data)
          this.profilePhoto = data.fileId
          // this..push(data.fileId)
          this.$emit('uploadFileId',data.fileId)
          oldFile.status='success',
          oldFile.message='上传成功...'
      }
    })
    })

  },
},
watch:{
  fileList:{
    handler(newVal,oldVal){
      this.newFileList = newVal
    },
    deep:true
  }
}
}
</script>

<style scoped lang="scss">
  .upload_content{
    background: #ffffff;
    .upload_title{
      color: #333333;
      font-size: 15px;
    }
  }
</style>

这里是单选上传,大家可以根据自己的业务需求自行修改,commonPhotoCompress 为工具类 代码如下:

// 将base64转为blob再转成file
const base64ToBlob = (imgBase64, file) => {
  const bytes = window.atob(imgBase64.split(',')[1])
  const ab = new ArrayBuffer(bytes.length)
  const ui8 = new Uint8Array(ab)
  for (let i = 0; i < bytes.length; i++) {
    ui8[i] = bytes.charCodeAt(i)
  }
  const blob = new Blob([ab], { type: file.type })
  return new File([blob], file.name, { type: file.type })
}

// 图片按比例转成成base64
const canvasToDataURL = (path, obj, file, callback) => {
  var img = new Image()
  img.src = path
  img.onload = function () {
    let that = this
    // 默认按比例压缩
    let w = that.width,
      h = that.height,
      scale = w / h
    w = obj.width || w
    h = obj.height || (w / scale)
    let quality = 0.7  // 默认图片质量为0.7
    // 生成canvas
    let canvas = document.createElement('canvas')
    let ctx = canvas.getContext('2d')
    // 创建属性节点
    let anw = document.createAttribute('width')
    anw.nodeValue = w
    let anh = document.createAttribute('height')
    anh.nodeValue = h
    canvas.setAttributeNode(anw)
    canvas.setAttributeNode(anh)
    ctx.drawImage(that, 0, 0, w, h)
    // 图像质量
    if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
      quality = obj.quality
    }
    // quality值越小,所绘制出的图像越模糊
    let base64 = canvas.toDataURL(file.type, quality)
    // 回调函数返回base64的值
    callback(base64)
  }
}

// 图片压缩
// 读取file对象,按比例压缩成对应的质量
// 返回对应的blob
const photoCompress = (file, obj = { quality: 0.6 }, cb) => {
  const fr = new FileReader()
  fr.onload = () => {
    console.log(file, 469)
    canvasToDataURL(fr.result, obj, file, (base64) => {
      if (cb) {
        cb(base64ToBlob(base64, file))
      }
    })
  }
  fr.readAsDataURL(file)
}


// 公共的图片质量转换
export const commonPhotoCompress = (file, callback) => {
  console.log('size',file.size/1024)
  if (file.size / 1024 < 1024) {
    // 小于1MB的不压缩
    callback(file)
  } else if (file.size / 1024 < 5000) {
    // 小于5MB的质量
    photoCompress(file, { quality: 0.4 }, callback)
  } else if (file.size / 1024 < 10000) {
    // 5MB-10MB的质量
    photoCompress(file, { quality: 0.2 }, callback)
  } else if (file.size / 1024 > 10000) {
    // 大于10MB的质量
    photoCompress(file, { quality: 0.1 }, callback)
  } else {
    // 其它
    photoCompress(file, { quality: 0.2 }, callback)
  }
}

记录一下自己的代码,好记性不如烂笔头,需要的拿走。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值