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

news/2024/7/10 1:22:12 标签: javascript, 前端, vue

二次封装element-plus上传组件

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

0 相关介绍

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

相关能力

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

相关文档

  • 西瓜播放器
  • element-plus

1 效果展示

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

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

2 组件主体

javascript"><template>
  <el-upload
    list-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>
        <img
          class="el-upload-list__item-thumbnail"
          :src="file.viewUrl"
          alt=""
          v-if="isShow"
        />
        <span class="el-upload-list__item-actions">
          <span
            class="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-dialog
    v-model="dialogVisible"
    style="width: 800px"
    @close="close"
    @open="open"
  >
    <el-image
      v-if="previewFile.type === 'image'"
      style="width: 100%; height: 400px"
      :src="previewFile.url"
      fit="contain"
      alt="Preview Image"
    />
    <videoComponent
      ref="videoRef"
      v-if="previewFile.type === 'video'"
      style="width: 100%; height: 400px"
      :url="previewFile.url"
      :poster="previewFile.viewUrl"
    />
    <audio
      ref="audioRef"
      v-if="previewFile.type === 'audio'"
      :src="previewFile.url"
      controls
      style="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"); // 也可以自己创建video
  video.src = url; // url地址 url跟 视频流是一样的
  const canvas = document.createElement("canvas"); // 获取 canvas 对象
  const ctx = canvas.getContext("2d"); // 绘制2d
  video.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"); // 也可以自己创建video
  audio.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"); // 也可以自己创建video
  img.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() {
  videoRef.value.changeUrl();
}
// 获取文件对象
function getFiles(): UploadFileNew[] {
  return fileList.value;
}
defineExpose({
  getFiles,
  verification,
  addFileList,
  handlePictureCardPreview,
  handleRemove,
});
</script>

3 视频组件

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

javascript"><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-form
    ref="ruleFormRef"
    :model="formData"
    label-width="120px"
    v-loading="submitLoading"
    element-loading-text="数据传输中..."
    style="margin-top: 20px;"
  >
    <el-form-item
      label="头像"
      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.niftyadmin.cn/n/4938235.html

相关文章

变压器故障诊断(python代码,逻辑回归/SVM/KNN三种方法同时使用,有详细中文注释)

代码运行要求&#xff1a;tensorflow版本>2.4.0,Python>3.6.0即可&#xff0c;无需修改数据路径。 1.数据集介绍&#xff1a; 采集数据的设备照片 变压器在电力系统中扮演着非常重要的角色。尽管它们是电网中最可靠的部件&#xff0c;但由于内部或外部的许多因素&#…

【CI/CD】Rancher K8s

Rancher & K8s Rancher 和 K8s 的关系是什么&#xff1f;K8s 全称为 Kubernetes&#xff0c;它是一个开源的&#xff0c;用于管理云平台中多个主机上的容器化的应用。而 Rancher 是一个完全开源的企业级多集群 Kubernetes 管理平台&#xff0c;实现了 Kubernetes 集群在混合…

NPCon:AI模型技术与应用峰会北京站 (参会感受)

8月12日&#xff0c;我有幸参加了在北京皇家格兰云天大酒店举行的“AI模型技术与应用峰会”。 这次会议邀请了很多技术大咖&#xff0c;他们围绕&#xff1a; 六大论点 大模型涌现&#xff0c;如何部署训练架构与算力芯片 LLM 应用技术栈与Agent全景解析 视觉GPU推理服务部署 …

vb+sql医院门诊管理系统设计与系统

摘要 信息时代已经来临,计算机应用于医院的日常管理,为医院的现代化带来了从未有过的动力和机遇,为医疗卫生领域的发展提供了无限的潜力。采用计算机管理信息系统已成为医院管理科学化和现代化的标志,给医院带来了明显的经济效益和社会效益。 本文介绍了数据库管理系统的…

linux系统服务学习(四)Linux系统下数据同步服务RSYNC

文章目录 Linux系统下数据同步服务RSYNC一、RSYNC概述1、什么是rsyncrsync的好姐妹数据同步过程 2、rsync特点3、rsync与scp的区别 二、RSYNC的使用1、基本语法2、本地文件同步3、远程文件同步思考&#xff1a;4、rsync作为系统服务Linux系统服务的思路&#xff1a; 三、任务解…

配置文件优先级解读

目录 概述 同级目录application配置文件优先级 application 以及bootstrap 优先级 不同级目录配置文件优先级 外部配置加载顺序 概述 SpringBoot除了支持properties格式的配置文件&#xff0c;还支持另外两种格式的配置文件。三种配置文件格式分别如下: properties格式…

vue2中实现响应式的原理object.defineproperty+发布定于模式的缺点

缺点&#xff1a; 1 不能监测到新增属性或者删除属性 2 不能检测到根据数组索引替换或新增的值。也无法监测数组索引的变化。 由于object.defineproperty&#xff08;对象&#xff0c;描述&#xff0c;对象的某个属性&#xff09;其实是对对象的某个属性进行修改&#xff0c;因…

日志解析方法汇总

各种样式的原始日志的解析方法. 一 文本格式 1. 字段间以空格分割, 字段中有空格时两端必加双引号 52.212.126.146 [11/Aug/2023:16:59:500800] "GET /?prefixtran&max2 HTTP/1.1" -- spark-sql解析字段(按csv格式读取) create temporary view tmp using csv o…