代码如下:
<script lang="ts" setup>
import { ElDialog, UploadProps, UploadFile, ElMessage } from "element-plus"
import { ref } from "vue"
const validImageFormats = ["jpg", "jpeg", "png"];//允许的文件后缀
//选择文件格式校验//并限制上传数量
const checkImageFormat =async (file) => {
console.log("文件格式校验");
console.log(file);
const fileFormat = file.name.split(".").pop().toLowerCase(); // 获取文件格式
if (!validImageFormats.includes(fileFormat)) {
ElMessage({ type: "error", message: "商品图片格式必须为 jpg/bmp/png" });
faceList.value = []; // 删除格式不符合的文件
return false; // 阻止文件上传
}
noUpload.value = true; // 设置为true阻止继续上传
// 判断图片大小,大于500kb进行压缩
if (file.size > 500 * 1024) {
console.log("图片大于500kb");
const reader = new FileReader();
reader.readAsDataURL(file.raw);
reader.onload = function () {
const img = new Image();
img.src = reader.result as string;
img.onload = async function () {
// 获取图片的宽高
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const maxWidth = 500; // 设置最大宽度为800px
const maxHeight = 500; // 设置最大高度为600px
let width = img.width;
let height = img.height;
// 计算压缩比例
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
// 设置canvas的宽高
canvas.width = width;
canvas.height = height;
// 将图片绘制到canvas上
ctx.drawImage(img, 0, 0, width, height);
// 将canvas转换为base64格式并上传
const compressedImageBase64 = canvas.toDataURL("image/jpg", 0.7); // 0.7为图片质量,可根据需求调整
// 在这里将 compressedImageBase64 上传到服务器或其他操作
};
};
} else {
}
return true; // 允许文件上传
};
const dialogImageUrl = ref(""); //预览图片路径
const dialogVisible = ref(false); //预览框可见
//删除
const handleRemove: UploadProps["onRemove"] = (file: UploadFile) => {
console.log("删除图片:");
console.log(faceList.value);
noUpload.value = false
};
//预览
const handlePictureCardPreview: UploadProps["onPreview"] = (file: UploadFile) => {
dialogImageUrl.value = file.url!;
dialogVisible.value = true;
};
const faceList = ref([])//图片列表
const noUpload = ref(false)//不再上传
</script>
<template>
<div>
<el-upload :class="{ disabled: noUpload }" :auto-upload="false" list-type="picture-card"
:on-preview="handlePictureCardPreview" :on-change="checkImageFormat" :on-remove="handleRemove" :limit="1"
ref="businessLicense" :file-list="faceList">
<el-icon v-if="faceList.length == 0">
<Plus />
</el-icon>
</el-upload>
<el-dialog v-model="dialogVisible">
<img w-full :src="dialogImageUrl" alt="Preview Image" />
</el-dialog>
</div>
</template>
<style scoped>
::v-deep .disabled .el-upload--picture-card {
display: none !important;
}
</style>