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

二次封装element-plus上传组件

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

0 相关介绍

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

相关能力

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

相关文档

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() {
  if (previewFile.value.type === "video") {
  	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>
相关推荐
aPurpleBerry3 分钟前
JS常用数组方法 reduce filter find forEach
javascript
GIS程序媛—椰子32 分钟前
【Vue 全家桶】7、Vue UI组件库(更新中)
前端·vue.js
DogEgg_00138 分钟前
前端八股文(一)HTML 持续更新中。。。
前端·html
ZL不懂前端41 分钟前
Content Security Policy (CSP)
前端·javascript·面试
乐闻x44 分钟前
ESLint 使用教程(一):从零配置 ESLint
javascript·eslint
木舟10091 小时前
ffmpeg重复回听音频流,时长叠加问题
前端
王大锤43911 小时前
golang通用后台管理系统07(后台与若依前端对接)
开发语言·前端·golang
我血条子呢1 小时前
[Vue]防止路由重复跳转
前端·javascript·vue.js
黎金安1 小时前
前端第二次作业
前端·css·css3
啦啦右一1 小时前
前端 | MYTED单篇TED词汇学习功能优化
前端·学习