上传图片功能,限制只允许上传2寸照

包含图片压缩,尺寸限制,加载动画,最后返回图片

<a-upload name="file" :action="imgUrl" :headers="headers" :data="datas" :show-upload-list="false" @change="handleChange"
    :beforeUpload="beforeImageUpload">
    <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
    <div v-else class="ant-upload">
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
    </div>
  </a-upload>

<script setup lang="ts">
import { ref, watch, watchEffect } from 'vue'
import * as imageConversion from 'image-conversion'
import { messageWarning } from '@/utils/antdMess'
const imageUrl = ref<string>('')
const certificate = ref<boolean>(false)
const loading = ref<boolean>(false);

const props = defineProps({
  imageUrl: String,
})
const emit = defineEmits<{
  (e: 'changeImage', value: String): void
}>();

watch(props, (value) => {
  imageUrl.value = value.imageUrl;
})
watchEffect(() => {
  imageUrl.value = props.imageUrl
})
const imgUrl = ref('路径')
const headers = { "Authorization": '' }
const datas = ref({ type: "avatar" })


const passFlag = ref(false)
const beforeImageUpload = (file, fileList) => {
  // console.log(file, fileList);
  return new Promise(async (resolve, reject) => {
    if (!file.type.includes('image')) {
      messageWarning('请上传图片')
      reject(new Error('请上传图片'))
      return
    } else {
        getDateUrl(file)
        setTimeout(() => {
          if (passFlag.value) {
            imageConversion.compressAccurately(file, 40).then(res => {
              resolve(res);
            });
          } else {
            messageWarning("请上传2寸证件照片")
            return reject(false)
          }
        }, 500)

    }

  })
}


let handleChange = (res) => {
  if (res.file.status == 'uploading') {
    loading.value = true
  }
  if (res.file.status == 'done') {
    loading.value = false
    emit("changeImage", res.file.response.data.path)
  }

}


// 尺寸
let mapPictureSize: any[] = []
const getDateUrl = (evt: any) => {
  const image: any = new Image();
  image.onload = function () {
    mapPictureSize[0] = this.width;
    mapPictureSize[1] = this.height;
    if (mapPictureSize[0] < mapPictureSize[1] && 0.65 < mapPictureSize[0] / mapPictureSize[1] && mapPictureSize[0] / mapPictureSize[1] < 0.75) {
      passFlag.value = true
    } else {
      passFlag.value = false
    }
  };
  image.src = URL.createObjectURL(evt);
}
</script>

img {
  width: 100%;
  height: 100%;
}

.ant-upload {
  width: 128px;
  height: 100%;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值