【篇三】在vue3上实现阿里云oss文件直传

之前写了两篇关于文件上传的文章
【篇一】使用springboot+vue实现阿里云oss上传
【篇二】使用springboot+vue实现阿里云oss文件直传,解决大文件分片上传问题

今天介绍一下在vue3中实现阿里云oss文件直传,主要是基于篇二中的源码进行修改,看具体代码

OssFileUpload组件

html 复制代码
<template>
  <div class="upload-file">
    <el-upload
        :multiple="multiple"
        :accept="accept.join(',')"
        action="#"
        :http-request="handleUpload"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="limit"
        :on-exceed="handleExceed"
        :show-file-list="false"
        :data="data"
        class="upload-file-uploader"
        ref="fileUpload"
    >
      <!-- 上传按钮 -->
      <el-button type="primary">选取文件</el-button>
      <template v-if="multiple"> (按住Ctrl键多选)</template>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip && fileList.length<=0">
      <span v-if="limit"> 1、文件数量限制为 <b style="color: #f56c6c">{{ limit }}个</b></span>
      <span v-if="fileSize"> 2、文件大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b><br></span>
      <span v-if="fileType"> 3、文件格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b><br></span>
    </div>

    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul" height="485">
      <li v-for="(file, index) in fileList" :key="file.uid || index " class="el-upload-list__item ele-upload-list__item-content">
        <el-link :href="file.url" :underline="false" target="_blank">
          <span class="`el-icon-d`ocument"> {{ file.name }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger" style="width: 50px">删除</el-link>
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script setup>
import {handleMD5} from '@/utils/md5';
import {generateOssPolicy} from "@/api/file/file";
import {POST} from "@/utils/request";

const props = defineProps({
  // 是否可多选
  multiple: {
    type: Boolean,
    default: true,
  },
  // 值
  value: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["doc", "xls", "xlsx", "ppt", "txt", "pdf"],
  },
  accept: {
    type: Array,
    default: () => [".doc", ".xls", ".xlsx", ".ppt", ".txt", ".pdf"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  // 是否重命名
  rename: {
    type: Boolean,
    default: true
  }
});

const {proxy} = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const fileList = ref([]);
const data = ref({});
const showTip = computed(
    () => props.isShowTip && (props.fileType || props.fileSize)
);
watch(() => [props.value, props.rename], ([val1, val2]) => {
  if (val1) {
    let temp = 1;
    // 首先将值转为数组
    const list = Array.isArray(val1) ? val1 : props.value.split(',');
    // 然后将数组转为对象数组
    fileList.value = list.map(item => {
      if (typeof item === "string") {
        item = {name: item.name, url: item.url};
      }
      item.uid = item.uid || new Date().getTime() + temp++;
      return item;
    });
  } else {
    fileList.value = [];
    return [];
  }
  if (val2) {
    data.value = {rename: val2}
  }
}, {deep: true, immediate: true});

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  //增加判断逻辑:如果是视频文件,获取视频分辨率
  const isVideo = file.type === "video/mp4" || file.type === "video/webm";
  if (isVideo) {
    // 创建一个视频元素
    const video = document.createElement('video');
    video.preload = 'metadata';
    // 设置视频源
    video.src = URL.createObjectURL(file);

    // 监听加载元数据完成
    video.onloadedmetadata = () => {
      URL.revokeObjectURL(video.src); // 释放URL对象
      const width = video.videoWidth;
      const height = video.videoHeight;
      // 获取视频时长
      const duration = video.duration;
      file.width = width;
      file.height = height;
      file.duration = duration;
      // 这里可以根据分辨率做进一步处理,例如检查分辨率是否符合要求
    };
  }
  proxy.$modal.loading("正在上传文件,请稍候...");
  number.value++;
  return true;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 删除文件
function handleDelete(index) {
  fileList.value.splice(index, 1);
  emit("update:value", listToString(fileList.value));
}


// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    emit("update:value", listToString(fileList.value));
    proxy.$modal.closeLoading();
  }
}

/** 上传操作 */
function handleUpload(file) {
  handleMD5(file.file).then(md5 => {
    const data = {
      fileName: file.file.name,
      md5: md5,
      rename: props.rename
      // 增加视频的分辨率、播放时长,后端接收后再通过回调接口返回,前端即可获取
      width: file.file.width,
      height: file.file.height,
      duration: file.file.duration,
    };
    generateOssPolicy(data).then((response) => {
      let data = response.data
      let formData = new FormData();
      formData.append('OSSAccessKeyId', data.accessKeyId);
      formData.append('signature', data.signature);
      formData.append('policy', data.policy);
      formData.append('key', data.filePath);
      formData.append('callback', data.callback);
      formData.append('success_action_status', 200);
      formData.append('file', file.file);

      POST(data.host, formData).then((res) => {
        let params = res.data
        if (params.code !== 200) {
          proxy.$modal.msgError(params.msg);
          return;
        }
        uploadList.value.push(params.data);
        uploadedSuccessfully();
        proxy.$modal.msgSuccess("上传成功");
      });
    })
  })
}

// 获取文件名称
function getFileName(name) {
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return "";
  }
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let str = "";
  separator = separator || ",";
  for (let i in list) {
    str += list[i].url + separator;
  }
  return str !== '' ? str.substring(0, str.length - 1) : '';
}

//暴露给父组件,否则无法获取值
defineExpose({
  fileList
})
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list {
  max-height: 420px;
  overflow-y: auto;
}
.el-upload__tip span {
  display: block;
  width: fit-content;
  line-height: 20px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>

父组件引用

js 复制代码
/** 提交按钮 */
function submitForm() {
  proxy.$refs["editForm"].validate(valid => {
    if (valid) {
      // 获取子组件的fileList
      form.value.files = proxy.$refs.upload.fileList
      if (!Array.isArray(form.value.files) || form.value.files.length <= 0) {
        proxy.$alert("请上传文件");
        return false;
      }
      //增加了多个文件属性字段
      form.value.download = form.value.files[0].url
      form.value.name = form.value.files[0].name
      form.value.userName = form.value.files[0].user
      form.value.md5 = form.value.files[0].md5
      form.value.size = form.value.files[0].size
      save(form.value).then(() => {
        proxy.$modal.msgSuccess("操作成功");
        open.value = false;
        getList();
      });
    }
  });
}

后端代码除组装callbackBody增加了几个参数外,逻辑基本相同,故省略。

相关推荐
CherishTaoTao1 天前
Vue3 keep-alive核心源码的解析
前端·vue3
宝子向前冲2 天前
纯前端生成PDF(jsPDF)并下载保存或上传到OSS
前端·pdf·html2canvas·oss·jspdf
vvw&2 天前
使用Ubuntu快速部署MinIO对象存储
linux·运维·服务器·ubuntu·minio·cos·oss
虞泽2 天前
鸢尾博客项目开源
java·spring boot·vue·vue3·博客
FinelyYang3 天前
antdesignvue + AWS-S3实现Minio大文件分片上传
aws·分片上传
前端杂货铺4 天前
简记Vue3(三)—— ref、props、生命周期、hooks
vue.js·vue3
静谧的美4 天前
vue3-element-admin 去掉登录
vue.js·前端框架·vue3·去掉登录
朝阳394 天前
vue3【组件封装】确认对话框 Modal
vue3·组件封装
朝阳394 天前
vue3【组件封装】消息提示 Toast
vue3·消息提示·组件封装