vue3+ts el-upload 封装

<template>
  <div class="upload-file" :style="sizes === 'small' ? 'display: flex' : ''">
    <transition-group
      v-if="sizes === 'small'"
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul"
      style="margin: 0; width: 50%"
    >
      <li v-for="(file, index) in fileList" :key="index" class="el-upload-list__item ele-upload-list__item-content">
        <el-link :underline="false" target="danger" @click="fileDownload(file.fileAddress, file.fileName)">
          <fileTypeImage style="width: 32px" :type="file.fileName.split('.').pop()" />
          <span class="el-icon-document">&nbsp;&nbsp;{{ getFileName(file.fileName) }} </span>
        </el-link>
        <div v-if="!disableds" class="ele-upload-list__item-content-action">
          <el-link :underline="false" type="danger" style="color: #165dff" @click="handleDelete(index)">删除</el-link>
        </div>
      </li>
    </transition-group>
    <el-upload
      v-if="!disableds"
      ref="fileUploadRef"
      :style="sizes === 'small' ? 'width: 50%;margin-left: 20px;' : ''"
      multiple
      drag
      :data="{ fileType: typeBusiness, ...dataBusiness }"
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      class="upload-file-uploader"
    >
      <template v-if="sizes !== 'small'">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">点击或拖拽到此处上传</div>
      </template>
      <template v-else>
        <div class="el-upload__text_small">重新上传</div>
      </template>
      <template #tip>
        <div class="el-upload__tip">支持格式: {{ fileType.join('、') }} &nbsp;&nbsp;最大 {{ fileSize }}MB</div>
      </template>
    </el-upload>
    <!-- 文件列表 -->
    <transition-group v-if="sizes !== 'small'" class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li v-for="(file, index) in fileList" :key="index" class="el-upload-list__item ele-upload-list__item-content">
        <el-link :underline="false" target="danger" @click="fileDownload(file.fileAddress, file.fileName)">
          <fileTypeImage style="width: 32px" :type="file.fileName.split('.').pop()" />
          <span class="el-icon-document">&nbsp;&nbsp;{{ getFileName(file.fileName) }} </span>
        </el-link>
        <div v-if="!disableds" class="ele-upload-list__item-content-action">
          <el-link :underline="false" type="danger" style="color: #165dff" @click="handleDelete(index)">删除</el-link>
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, toRefs, onMounted, defineProps, defineEmits } from 'vue';
import fileTypeImage from './fileTypeImage.vue';
import { propTypes } from '@/utils/propTypes';
import { globalHeaders } from '@/utils/request';
import request from '@/utils/request';
import load from '@/plugins/download';

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  // 跟随图片上传的业务数据
  dataBusiness: propTypes.object.def({}),
  // 跟随图片上传的业务类型
  typeBusiness: propTypes.string.def('abc'),
  // 数量限制
  limit: propTypes.number.def(5),
  // 大小限制(MB)
  fileSize: propTypes.number.def(5),
  // 文件类型, 例如['png', 'jpg', 'jpeg']s
  fileType: propTypes.array.def(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'txt', 'pdf', 'png', 'jpeg', 'jpg']),
  // 是否显示提示
  isShowTip: propTypes.bool.def(true),
  //是否显示el-upload
  disableds: {
    type: Boolean,
    default: false
  },
  //大小
  sizes: {
    type: String,
    default: ''
  }
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['update:modelValue']);
const number = ref(0);
const uploadList = ref<any[]>([]);

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(baseUrl + '/file/upload'); // 上传文件服务器地址
const headers = ref(globalHeaders());

const fileList = ref<any[]>([]);

const fileUploadRef = ref<ElUploadInstance>();

watch(
  () => props.modelValue,
  (val: any) => {
    if (val && val.length) {
      fileList.value = val;
      // let temp = 1;
      // fileList.value = val.map((item: any) => {
      //   item = { fileName: item.fileName, url: item.url, ossId: item.ossId };
      //   item.uid = item.uid || new Date().getTime() + temp++;
      //   return item;
      // });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);

// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
  // 校检文件类型
  if (props.fileType.length) {
    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;
    }
  }
  proxy?.$modal.loading('正在上传文件,请稍候...');
  number.value++;
  return true;
};

// 上传成功回调
const handleUploadSuccess = (res: any, file: UploadFile) => {
  if (res.code === 200) {
    uploadList.value.push({ ...res.data });
    uploadedSuccessfully();
  } else {
    number.value--;
    proxy?.$modal.closeLoading();
    proxy?.$modal.msgError(res.msg);
    fileUploadRef.value?.handleRemove(file);
    uploadedSuccessfully();
  }
};

// 文件下载
const fileDownload = (url: string, name: string) => {
  request({
    url: '/file/private/url',
    method: 'post',
    data: {
      fileAddress: url
    }
  }).then((res: any) => {
    if (res.code == 200) {
      load.downloadGet(res.data.fileAddress, name);
    }
  });
};

// 删除文件
const handleDelete = (index: number) => {
  fileList.value.splice(index, 1);
  emit('update:modelValue', listToString(fileList.value));
};

// 上传结束处理
const 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:modelValue', listToString(fileList.value));
    proxy?.$modal.closeLoading();
  }
};

// 获取文件名称
const getFileName = (name: string) => {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf('/') > -1) {
    return name.slice(name.lastIndexOf('/') + 1);
  } else {
    return name;
  }
};

// 对象转成指定字符串分隔
const listToString = (list: any[], separator?: string) => {
  return list.map((e) => ({
    fileName: e.fileName,
    dataKey: e.dataKey,
    fileAddress: e.fileAddress
  }));

  // return list.map((e) => ({
  //   name: e.name,
  //   ossId: e.ossId,
  //   url: e.url
  // }));
};

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

// 上传失败
const handleUploadError = () => {
  proxy?.$modal.msgError('上传文件失败');
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
  width: 100%;
  position: relative;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  cursor: hand;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  padding: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

.el-upload__tip {
  color: #86909c;

  margin-top: 0px;
}

:deep(.el-upload-dragger) {
  background-color: #e5e6eb7a;
  padding: 14px 10px;
}

.el-icon--upload {
  margin-bottom: 0;
  font-size: 40px;
}

.el-upload__text_small {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
<template>
  <div class="upload-file">
    <el-upload
      v-if="!disableds"
      ref="fileUploadRef"
      multiple
      drag
      :data="{ fileType: typeBusiness, ...dataBusiness }"
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      class="upload-file-uploader upload-demo"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">点击或拖拽到此处上传</div>
      <template #tip>
        <div class="el-upload__tip">支持格式: {{ fileType.join('、') }} &nbsp;&nbsp;最大 {{ fileSize }}MB</div>
      </template>
    </el-upload>
    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li v-for="(file, index) in fileList" :key="index" class="el-upload-list__item ele-upload-list__item-content">
        <el-link :underline="false" target="danger" @click="fileDownload(file.fileAddress, file.fileName)">
          <fileTypeImage style="width: 32px" :type="file.fileName.split('.').pop()" />
          <span class="el-icon-document">&nbsp;&nbsp;{{ getFileName(file.fileName) }} </span>
        </el-link>
        <div v-if="!disableds" class="ele-upload-list__item-content-action">
          <el-link :underline="false" type="danger" style="color: #165dff" @click="handleDelete(index)">删除</el-link>
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, toRefs, onMounted, defineProps, defineEmits } from 'vue';
import fileTypeImage from './fileTypeImage.vue';
import { propTypes } from '@/utils/propTypes';
import { globalHeaders } from '@/utils/request';
import request from '@/utils/request';
import load from '@/plugins/download';

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  // 跟随图片上传的业务数据
  dataBusiness: propTypes.object.def({}),
  // 跟随图片上传的业务类型
  typeBusiness: propTypes.string.def('abc'),
  // 数量限制
  limit: propTypes.number.def(5),
  // 大小限制(MB)
  fileSize: propTypes.number.def(5),
  // 文件类型, 例如['png', 'jpg', 'jpeg']s
  fileType: propTypes.array.def(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'txt', 'pdf', 'png', 'jpeg', 'jpg']),
  // 是否显示提示
  isShowTip: propTypes.bool.def(true),
  //是否显示el-upload
  disableds: {
    type: Boolean,
    default: false
  }
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['update:modelValue']);
const number = ref(0);
const uploadList = ref<any[]>([]);

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(baseUrl + '/file/upload'); // 上传文件服务器地址
const headers = ref(globalHeaders());

const fileList = ref<any[]>([]);

const fileUploadRef = ref<ElUploadInstance>();

watch(
  () => props.modelValue,
  (val: any) => {
    if (val && val.length) {
      fileList.value = val;
      // let temp = 1;
      // fileList.value = val.map((item: any) => {
      //   item = { fileName: item.fileName, url: item.url, ossId: item.ossId };
      //   item.uid = item.uid || new Date().getTime() + temp++;
      //   return item;
      // });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);

// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
  // 校检文件类型
  if (props.fileType.length) {
    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;
    }
  }
  proxy?.$modal.loading('正在上传文件,请稍候...');
  number.value++;
  return true;
};

// 上传成功回调
const handleUploadSuccess = (res: any, file: UploadFile) => {
  if (res.code === 200) {
    uploadList.value.push({ ...res.data });
    uploadedSuccessfully();
  } else {
    number.value--;
    proxy?.$modal.closeLoading();
    proxy?.$modal.msgError(res.msg);
    fileUploadRef.value?.handleRemove(file);
    uploadedSuccessfully();
  }
};

// 文件下载
const fileDownload = (url: string, name: string) => {
  request({
    url: '/file/private/url',
    method: 'post',
    data: {
      fileAddress: url
    }
  }).then((res: any) => {
    if (res.code == 200) {
      load.downloadGet(res.data.fileAddress, name);
    }
  });
};

// 删除文件
const handleDelete = (index: number) => {
  fileList.value.splice(index, 1);
  emit('update:modelValue', listToString(fileList.value));
};

// 上传结束处理
const 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:modelValue', listToString(fileList.value));
    proxy?.$modal.closeLoading();
  }
};

// 获取文件名称
const getFileName = (name: string) => {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf('/') > -1) {
    return name.slice(name.lastIndexOf('/') + 1);
  } else {
    return name;
  }
};

// 对象转成指定字符串分隔
const listToString = (list: any[], separator?: string) => {
  return list.map((e) => ({
    fileName: e.fileName,
    dataKey: e.dataKey,
    fileAddress: e.fileAddress
  }));

  // return list.map((e) => ({
  //   name: e.name,
  //   ossId: e.ossId,
  //   url: e.url
  // }));
};

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

// 上传失败
const handleUploadError = () => {
  proxy?.$modal.msgError('上传文件失败');
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
  width: 100%;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  cursor: hand;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  padding: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

.el-upload__tip {
  color: #86909c;

  margin-top: 0px;
}

:deep(.el-upload-dragger) {
  background-color: #e5e6eb7a;
  padding: 14px 10px;
}

.el-icon--upload {
  margin-bottom: 0;
  font-size: 40px;
}
</style>
<template>
  <img v-if="type == 'jpeg'" src="@/assets/fileTypeImage/jpeg.png" />
  <img v-else-if="type == 'jpg'" src="@/assets/fileTypeImage/jpg.png" />
  <img v-else-if="type == 'ppt'" src="@/assets/fileTypeImage/p.png" />
  <img v-else-if="type == 'pdf'" src="@/assets/fileTypeImage/pdf.png" />
  <img v-else-if="type == 'png'" src="@/assets/fileTypeImage/png.png" />
  <img v-else-if="type == 'txt'" src="@/assets/fileTypeImage/txt.png" />
  <img v-else-if="type == 'docx' || type == 'doc'" src="@/assets/fileTypeImage/w.png" />
  <img v-else-if="type == 'xlsx' || type == 'xls'" src="@/assets/fileTypeImage/x.png" />
  <img v-else-if="type == 'zip'" src="@/assets/fileTypeImage/zip.png" />
</template>

<script setup lang="ts">
import { reactive, ref, toRefs, onMounted, defineProps, defineEmits } from 'vue';
import { propTypes } from '@/utils/propTypes';

const props = defineProps({
  type: propTypes.string.def(''),
  fileType: propTypes.array.def(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'txt', 'pdf', 'png', 'jpeg', 'jpg', 'zip'])
});
</script>

<style scoped lang="scss">
img {
  width: 100%;
}
</style>
  <myUpload
    v-model="item.fileParams"
    :disableds="routeParams.type === 'view'"
    type-business="projectAnnex"
    :limit="1"
    :file-type="['xls', 'xlsx']"
    style="width: 100%"
  />

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一路向北. 

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

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

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

打赏作者

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

抵扣说明:

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

余额充值