vue3+el-upload实现图片数量、格式、大小校验,压缩上传

代码如下:

<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>

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,下面是使用 Vue3+Element-plus 编写图片上传的代码及注释: ```html <template> <div> <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false" :on-success="handleSuccess" :before-upload="beforeAvatarUpload" > <!-- 上传按钮 --> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </div> </template> <script> import { ref } from 'vue' export default { name: 'AvatarUpload', setup() { const imageUrl = ref('') // 上传前的校验 const beforeAvatarUpload = (file) => { const isJPG = file.type === 'image/jpeg' const isPNG = file.type === 'image/png' const isLt2M = file.size / 1024 / 1024 < 2 if (!isJPG && !isPNG) { this.$message.error('上传头像图片只能是 JPG/PNG 格式!') return false } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!') return false } return true } // 上传成功的回调 const handleSuccess = (res) => { if (res.code === '200') { imageUrl.value = res.data.url this.$message.success('上传成功!') } else { this.$message.error('上传失败,请重试!') } } return { imageUrl, beforeAvatarUpload, handleSuccess } } } </script> <style scoped> .avatar-uploader { display: flex; justify-content: center; align-items: center; width: 120px; height: 120px; border-radius: 50%; border: 1px dashed #ccc; background-color: #f9fafc; cursor: pointer; } .avatar { width: 120px; height: 120px; border-radius: 50%; object-fit: cover; } .avatar-uploader-icon { font-size: 28px; color: #8c939d; } </style> ``` 注释: - `el-upload` 是 Element-plus 中的上传组件,`action` 属性指定上传接口地址,`show-file-list` 属性指定是否显示上传文件列表,`on-success` 属性指定上传成功的回调函数,`before-upload` 属性指定上传前的校验函数; - `img` 标签用于展示上传成功后的图片,属性 `v-if="imageUrl"` 判断 `imageUrl` 是否存在,如果存在则显示图片,否则显示上传按钮; - `i` 标签用于显示上传按钮,属性 `v-else` 表示如果 `imageUrl` 不存在,则显示按钮; - `ref` 是 Vue3 中用于创建响应式数据的方法; - `beforeAvatarUpload` 方法用于上传前的校验,判断文件类型和大小是否符合要求; - `handleSuccess` 方法用于上传成功的回调,在回调中将上传成功的图片地址赋值给 `imageUrl`,并提示上传成功; - `setup` 函数是 Vue3 中的新特性,用于组件的选项设置,返回一个对象,包含组件中需要用到的数据和方法; - `return` 中的数据和方法,会被 Vue3 自动注入到组件的模板中使用; - `style` 标签的 `scoped` 属性表示样式仅作用于当前组件中的元素,不会影响到其他组件的样式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒾酒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值