二次封装element-plus上传组件,提供校验、回显等功能

二次封装element-plus上传组件

  • 0 相关介绍
  • 1 效果展示
  • 2 组件主体
  • 3 视频组件
  • 4 Demo

0 相关介绍

基于element-plus框架,视频播放器使用西瓜视频播放器组件

相关能力

  • 提供图片、音频、视频的预览功能
  • 提供是否为空、文件类型、文件大小、文件数量、图片宽高校验
  • 提供图片回显功能,并保证回显的文件不会重新上传
  • 提供达到数量限制不显示element自带的加号

相关文档

  • 西瓜播放器
  • element-plus

1 效果展示

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2 组件主体

<template><el-uploadlist-type="picture-card":auto-upload="false":on-change="onChange":on-remove="onChange":multiple="props.multiple":limit="props.limit":accept="accept"ref="elUploadElement":file-list="fileList":id="fileUploadId"><el-icon><Plus /></el-icon><template #file="{ file }"><div><imgclass="el-upload-list__item-thumbnail":src="file.viewUrl"alt=""v-if="isShow"/><span class="el-upload-list__item-actions"><spanclass="el-upload-list__item-preview"@click="handlePictureCardPreview(file)"><el-icon><zoom-in /></el-icon></span><span class="el-upload-list__item-delete" @click="handleRemove(file)"><el-icon><Delete /></el-icon></span></span></div></template><template #tip><div class="el-upload__tip">{{ tip }}</div></template></el-upload><!-- 文件预览弹窗 --><el-dialogv-model="dialogVisible"style="width: 800px"@close="close"@open="open"><el-imagev-if="previewFile.type === 'image'"style="width: 100%; height: 400px":src="previewFile.url"fit="contain"alt="Preview Image"/><videoComponentref="videoRef"v-if="previewFile.type === 'video'"style="width: 100%; height: 400px":url="previewFile.url":poster="previewFile.viewUrl"/><audioref="audioRef"v-if="previewFile.type === 'audio'":src="previewFile.url"controlsstyle="width: 100%; height: 400px"/></el-dialog>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { Delete, Plus, ZoomIn } from "@element-plus/icons-vue";
import type { UploadFile } from "element-plus";
// 多个组件同时使用的时候做区分
const fileUploadId = ref(`ID${Math.floor(Math.random() * 100000)}`);
type UploadFileNew = {[Property in keyof UploadFile]: UploadFile[Property];
} & {type: string;viewUrl: string | undefined;needUpload: boolean;duration: number;width: number;height: number;
};const imageRegex = RegExp(/(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)/);
const audioRegex = RegExp(/(mp3|wav|flac|ogg|aac|wma)/);
const videoRegex = RegExp(/(avi|wmv|mpeg|mp4|m4v|mov|asf|flv|f4v|rmvb|rm|3gp|vob)/
);
// 导入视频组件
import videoComponent from "./videoComponent.vue";
const props = defineProps({// 数量限制limit: {type: Number,default: 1,},// 是否多选multiple: {type: Boolean,default: false,},// 要选择的文件类型fileType: {type: String,required: true,validator(value: string) {return ["audio", "image", "video"].includes(value);},},// 追加的提示appendTip: {type: String,default: "",},widthLimit: {type: Number,default: 0,},heightLimit: {type: Number,default: 0,},
});
// 可上传文件类型
const accept = ref("");
// 最大上传文件大小
const maxSize = ref(0);
const tip = ref("");
// 根据类型设置默认值
if (props.fileType) {switch (props.fileType) {case "image":accept.value = ".png, .jpg, .jpeg";maxSize.value = 20;tip.value = `请上传${accept.value}格式的文件,图片大小不能超过${maxSize.value}MB。${props.appendTip}`;break;case "audio":accept.value = ".mp3, .wma, .aac, .flac, .ape";maxSize.value = 500;tip.value = `请上传${accept.value}格式的文件,音频大小不能超过${maxSize.value}MB。${props.appendTip}`;break;case "video":accept.value = ".mp4, .rmvb, .avi, .mov";maxSize.value = 500;tip.value = `请上传${accept.value}格式的文件,视频大小不能超过${maxSize.value}MB。${props.appendTip}`;break;case "musiVideo":accept.value = ".mp4, .rmvb, .avi, .mov, .mp3, .wma, .aac, .flac, .ape";maxSize.value = 500;tip.value = `请上传${accept.value}格式的文件,音视频大小不能超过${maxSize.value}MB。${props.appendTip}`;break;default:throw new Error("类型错误");}
}
const isShow = ref(true);
const elUploadElement = ref();
// 控制图片预览的路径
const previewFile = ref();
// 控制是否显示图片预览的弹窗
const dialogVisible = ref(false);
// 双向绑定的文件列表
const fileList = ref<UploadFileNew[]>([]);
// 定义组件ref
const videoRef = ref(),audioRef = ref();
async function onChange(uploadFile: UploadFileNew,uploadFiles: UploadFileNew[]
) {// 如果是远程原件不需要任何处理if (!uploadFile.name) return;isShow.value = false;const suffix = uploadFile.name.split(".").at(-1) as string;if (videoRegex.test(suffix.toLocaleLowerCase())) {const res = (await findvideodetail(uploadFile.url as string)) as {viewUrl: string;duration: number;};uploadFile.type = "video";uploadFile.viewUrl = res.viewUrl;uploadFile.duration = res.duration;} else if (imageRegex.test(suffix)) {uploadFile.type = "image";uploadFile.viewUrl = uploadFile.url;const res = (await findImageDetail(uploadFile.url as string)) as {width: number;height: number;};uploadFile.width = res.width;uploadFile.height = res.height;} else if (audioRegex.test(suffix)) {uploadFile.type = "audio";uploadFile.viewUrl = new URL("@/assets/goods/audio.svg",import.meta.url).href;const res = (await findAudioDetail(uploadFile.url as string)) as {duration: number;};uploadFile.duration = res.duration;}console.log(uploadFile);uploadFile.needUpload = true;fileList.value = uploadFiles;isShow.value = true;verifyLength();
}// 删除文件
function handleRemove(uploadFile: UploadFile) {elUploadElement.value.handleRemove(uploadFile);verifyLength();
}// 检验已选择的文件数量是否超过阈值,并做显示/隐藏处理
function verifyLength() {const element = document.querySelector(`#${fileUploadId.value} .el-upload--picture-card`) as HTMLDivElement;console.log(fileUploadId.value, element);if (fileList.value.length === props.limit) {element.style.visibility = "hidden";} else {element.style.visibility = "visible";}
}// 预览文件
const handlePictureCardPreview = (file: UploadFile) => {previewFile.value = file;dialogVisible.value = true;
};//截取视频第一帧作为播放前默认图片
function findvideodetail(url: string) {const video = document.createElement("video"); // 也可以自己创建videovideo.src = url; // url地址 url跟 视频流是一样的const canvas = document.createElement("canvas"); // 获取 canvas 对象const ctx = canvas.getContext("2d"); // 绘制2dvideo.crossOrigin = "anonymous"; // 解决跨域问题,也就是提示污染资源无法转换视频video.currentTime = 1; // 第一帧return new Promise((resolve) => {video.oncanplay = () => {canvas.width = video.clientWidth || video.width || 320; // 获取视频宽度canvas.height = video.clientHeight || video.height || 240; //获取视频高度// 利用canvas对象方法绘图ctx!.drawImage(video, 0, 0, canvas.width, canvas.height);// 转换成base64形式const viewUrl = canvas.toDataURL("image/png"); // 截取后的视频封面resolve({viewUrl: viewUrl,duration: Math.ceil(video.duration),width: video.width,height: video.height,});video.remove();canvas.remove();};});
}
//截取视频第一帧作为播放前默认图片
function findAudioDetail(url: string) {const audio = document.createElement("audio"); // 也可以自己创建videoaudio.src = url; // url地址 url跟 视频流是一样的audio.crossOrigin = "anonymous"; // 解决跨域问题,也就是提示污染资源无法转换视频return new Promise((resolve) => {audio.oncanplay = () => {resolve({duration: Math.ceil(audio.duration),});audio.remove();};});
}
//
function findImageDetail(url: string) {const img = document.createElement("img"); // 也可以自己创建videoimg.src = url; // url地址 url跟 视频流是一样的return new Promise((resolve) => {img.onload = () => {resolve({width: img.width,height: img.height,});img.remove();};});
}type validateReturnValue = {code: number;success: boolean;msg: string;
};
// 验证文件格式
function verification(): validateReturnValue {if (fileList.value.length <= 0) {return {code: 0,success: false,msg: "请选择上传文件",};}if (fileList.value.length > props.limit) {return {code: 0,success: false,msg: `文件数量超出限制,请上传${props.limit}以内的文件`,};}for (let i = 0; i < fileList.value.length; i++) {const element = fileList.value[i];if (!element.needUpload) break;const suffix = element.name.split(".").at(-1) as string;if (!accept.value.includes(suffix.toLowerCase())) {return {code: 0,success: false,msg: `文件类型不正确,请上传${accept.value}类型的文件`,};}if ((element.size as number) / 1024 / 1024 > maxSize.value) {return {code: 0,success: false,msg: "文件大小超出限制",};}if (element.type === "image") {if (props.widthLimit && element.width != props.widthLimit) {return {code: 0,success: false,msg: `图片宽度不等于${props.widthLimit}像素`,};}if (props.heightLimit && element.height != props.heightLimit) {return {code: 0,success: false,msg: `图片高度不等于${props.heightLimit}像素`,};}}}return {code: 200,success: true,msg: "格式正确",};
}// 添加远程图片
async function addFileList(url: string, name?: string) {const uploadFile: any = {url,name,};const suffix = url.split(".").at(-1) as string;if (videoRegex.test(suffix.toLocaleLowerCase())) {const res = (await findvideodetail(url)) as {viewUrl: string;};uploadFile.type = "video";uploadFile.viewUrl = res.viewUrl;} else if (imageRegex.test(suffix)) {uploadFile.type = "image";uploadFile.viewUrl = uploadFile.url;} else if (audioRegex.test(suffix)) {uploadFile.type = "audio";uploadFile.viewUrl = new URL("@/assets/goods/audio.svg",import.meta.url).href;}uploadFile.needUpload = false;fileList.value.push(uploadFile);verifyLength();
}
// 关闭弹窗的时候停止音视频的播放
function close() {if (previewFile.value.type === "audio") {audioRef.value.pause();}if (previewFile.value.type === "video") {videoRef.value.pause();}
}
// 打开弹窗的时候修改视频路径和封面
function open() {if (previewFile.value.type === "video") {videoRef.value.changeUrl();}
}
// 获取文件对象
function getFiles(): UploadFileNew[] {return fileList.value;
}
defineExpose({getFiles,verification,addFileList,handlePictureCardPreview,handleRemove,
});
</script>

3 视频组件

<script setup lang="ts">
import { onMounted } from "vue";import Player from "xgplayer";
import "xgplayer/dist/index.min.css";const props = defineProps({// 视频路径url: {type: String,},// 封皮poster: {type: String,},
});
let player: any;
onMounted(() => {player = new Player({id: "mse",lang: "zh",// 默认静音volume: 0,autoplay: false,screenShot: true,videoAttributes: {crossOrigin: "anonymous",},url: props.url,poster: props.poster,//传入倍速可选数组playbackRate: [0.5, 0.75, 1, 1.5, 2],});
});
// 对外暴露暂停事件
function pause() {player.pause();
}
// 对外暴露修改视频源事件
function changeUrl() {player.playNext({url: props.url,poster: props.poster,});
}
defineExpose({ pause, changeUrl });
</script><template><div id="mse" />
</template><style scoped>
#mse {flex: auto;margin: 0px auto;
}
</style>

4 Demo

<script setup lang="ts">
import { ref, onMounted } from "vue";
import FileUpload from "./FileUpload/index.vue";
import type { FormInstance } from "element-plus";
// el-form实例
const ruleFormRef = ref();
// form绑定参数
const formData = ref({headImage: undefined,headImageList: [],
});// ------上传文件校验用 start-------
const FileUploadRef = ref();
let uploadRules = ref();
const isShowUpLoad = ref(true);
onMounted(() => {isShowUpLoad.value = false;uploadRules = ref([{validator(rule: any, value: any, callback: any) {const res = FileUploadRef.value.verification();if (!res.success) {callback(new Error(res.msg));}setTimeout(() => {callback();}, 500);},trigger: "blur",},// 需要显示出星号,但是由于没有做数据绑定,所以放在后边{ required: true, message: "请上传头像", trigger: "blur" },]);isShowUpLoad.value = true;
});
// ------上传文件校验用 end-------const submitLoading = ref(false);
function submitForm(ruleFormRef: FormInstance) {// 避免必需的校验无法通过formData.value.headImageList = FileUploadRef.value.getFiles();ruleFormRef.validate(async (valid) => {if (valid) {submitLoading.value = true;const params = { ...formData.value };// 单文件这么写,多文件需要循环if (params.headImageList[0].needUpload)params.headImage = await uploadFile(params.headImageList[0].raw);delete params.headImageList;submitLoading.value = false;}});
}
function uploadFile(file: File) {return "路径";
}
</script>
<!--  -->
<template><el-formref="ruleFormRef":model="formData"label-width="120px"v-loading="submitLoading"element-loading-text="数据传输中..."style="margin-top: 20px;"><el-form-itemlabel="头像"prop="headImageList":rules="uploadRules"v-if="isShowUpLoad"><FileUpload ref="FileUploadRef" :multiple="false" fileType="image" /></el-form-item><el-form-item label=""><el-button>取 消</el-button><el-button type="primary" @click="submitForm(ruleFormRef)">确 认</el-button></el-form-item></el-form>
</template>
<style lang="scss" scoped></style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/67842.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

实录分享 | 使用Prometheus和Grafana监控Alluxio运行状况

欢迎来到【微直播间】&#xff0c;2min纵览大咖观点 本次分享主要包括三个方面&#xff1a; Prometheus&Grafana简介环境搭建手动调优 一、 Prometheus&Grafana简介关于Prometheus&#xff1a; Prometheus 是一个开源的完整监控解决方案&#xff0c;其对传统监控系…

js操作剪贴板讲解

文章目录 复制&#xff08;剪切&#xff09;到剪贴板Document.execCommand()Clipboard复制Clipboard.writeText()Clipboard.write() copy&#xff0c;cut事件 从剪贴板进行粘贴document.execCommand(paste)Clipboard粘贴Clipboard.readText()Clipboard.read() paste 事件 安全性…

领航未来!探索开源无人机与5G组网的前沿技术

近年来无人机行业高速发展&#xff0c;无人机被广泛应用于航拍、农业、电力、消防、科研等领域。随着无人机市场不断增长&#xff0c;其对实时超高清图传、远程低时延控制、海量数据处理等需求也在不断扩张&#xff0c;这无疑给通信链路带来了巨大的挑战。 为应对未来的需求变…

NLP文本匹配任务Text Matching [有监督训练]:PointWise(单塔)、DSSM(双塔)、Sentence BERT(双塔)项目实践

NLP文本匹配任务Text Matching [有监督训练]&#xff1a;PointWise&#xff08;单塔&#xff09;、DSSM&#xff08;双塔&#xff09;、Sentence BERT&#xff08;双塔&#xff09;项目实践 0 背景介绍以及相关概念 本项目对3种常用的文本匹配的方法进行实现&#xff1a;Poin…

数据分析两件套ClickHouse+Metabase(一)

ClickHouse篇 安装ClickHouse ClickHouse有中文文档, 安装简单 -> 文档 官方提供了四种包的安装方式, deb/rpm/tgz/docker, 自行选择适合自己操作系统的安装方式 这里我们选deb的方式, 其他方式看文档 sudo apt-get install -y apt-transport-https ca-certificates dirm…

【冒泡排序及其优化】

冒泡排序及其优化 冒泡排序核心思想 冒泡排序的核⼼思想就是&#xff1a;两两相邻的元素进⾏⽐较 1题目举例 给出一个倒序数组&#xff1a;arr[10]{9,8,7,6,5,4,3,2,1,0} 请排序按小到大输出 1.1题目分析 这是一个完全倒序的数组&#xff0c;所以确定冒泡排序的趟数&#xff0…

如何手动创建可信任证书DB并配置 nss-config-dir

以阿里云免费邮箱为例 1. 如何下载证书链 证书链说明 使用 gnutls gnutls-cli --print-cert smtp.aliyun.com:465 < /dev/null > aliyun-chain.certs使用 openssl showcerts $ echo -n | openssl s_client -showcerts -connect smtp.aliyun.com:465 | sed -ne /-BE…

机器学习笔记之优化算法(十三)关于二次上界引理

机器学习笔记之优化算法——关于二次上界引理 引言回顾&#xff1a;利普希兹连续梯度下降法介绍 二次上界引理&#xff1a;介绍与作用二次上界与最优步长之间的关系二次上界引理证明过程 引言 本节将介绍二次上界的具体作用以及它的证明过程。 回顾&#xff1a; 利普希兹连续…

Rabbitmq延迟消息

目录 一、延迟消息1.基于死信实现延迟消息1.1 消息的TTL&#xff08;Time To Live&#xff09;1.2 死信交换机 Dead Letter Exchanges1.3 代码实现 2.基于延迟插件实现延迟消息2.1 插件安装2.2 代码实现 3.基于延迟插件封装消息 一、延迟消息 延迟消息有两种实现方案&#xff…

postman入门基础 —— 接口测试流程

一、编写接口测试计划 接口测试计划和功能测试计划目标一致&#xff0c;都是为了确认需求、确定测试环境、确定测试方法&#xff0c;为设计测试用例做准备&#xff0c;初步制定接口测试进度方案。一般来说&#xff0c;接口测试计划包括概述、测试资源、测试功能、测试重点、测试…

YOLOv5改进系列(21)——替换主干网络之RepViT(清华 ICCV 2023|最新开源移动端ViT)

【YOLOv5改进系列】前期回顾: YOLOv5改进系列(0)——重要性能指标与训练结果评价及分析 YOLOv5改进系列(1)——添加SE注意力机制 YOLOv5改进系列(2

08-1_Qt 5.9 C++开发指南_QPainter绘图

文章目录 前言1. QPainter 绘图系统1.1 QPainter 与QPaintDevice1.2 paintEvent事件和绘图区1.3 QPainter 绘图的主要属性 2. QPen的主要功能3. QBrush的主要功能4. 渐变填充5. QPainter 绘制基本图形元件5.1 基本图像元件5.2 QpainterPath的使用 前言 本章所介绍内容基本在《…