van-uploader上传图片,组件自带预览图片,不管失败还是成功,都会展示图片
可以在上传图片函数中,通过file.status和file.message使用加载loading过渡
<van-field name="uploader" label="电子照片上传" required :rules="[{ required: true, message: '请上传照片' }]">
<template #input>
<div class="middle-img">
<van-uploader v-model="fileList" action="https://XXXXXX/" upload-icon="plus" max-count="1"
:before-read="beforeRead" :after-read="uploadImage" accept="image/jpeg" :max-size="400 * 1024"
:preview-size="100" />
<div class="img-tip">小二寸,小于400KB,<br>
宽度413像素,高度551像素,<br>
JPG格式。</div>
</div>
</template>
</van-field>
const fileList = ref([])
const imgHash = ref('')
const beforeRead = (file) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = function () {
const isJpg = file.type === 'image/jpeg' || file.type === 'image/jpg';
const isSizeValid = file.size / 1024 < 400;
const isWidthValid = img.width >= 403 && img.width <= 423;
const isHeightValid = img.height >= 541 && img.height <= 561;
// const isDimensionValid = img.width === 413 && img.height === 551;
if (!isJpg) {
// resolve()
showToast('图片格式必须为JPG');
reject();
} else if (!isSizeValid) {
showToast('图片大小不能超过400KB');
reject();
} else if (!isWidthValid || !isHeightValid) {
showToast('图片尺寸必须为413x551像素');
reject();
}
resolve();
}
img.src = URL.createObjectURL(file)
})
}
const uploadImage = async (file) => {
const formData = new FormData()
formData.append('file', file.file)
formData.append('token', getToken.value)
file.status = 'uploading'
file.message = '上传中...'
upImg(formData)
.then(response => {
if (response.hash.length < 28) {
fileList.value = []
showToast('图片上传失败了,请重新上传')
file.status = ""
} else {
imgHash.value = response.hash
showToast('图片上传成功')
file.status = ""
}
})
.catch(error => {
fileList.value = []
showToast('图片上传失败,请重新上传')
file.status = ""
})
}