包含图片压缩,尺寸限制,加载动画,最后返回图片
<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;
}