index.vue 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. <template>
  2. <div class="upload-file">
  3. <el-upload
  4. ref="fileUploadRef"
  5. multiple
  6. :action="uploadFileUrl"
  7. :before-upload="handleBeforeUpload"
  8. :file-list="fileList"
  9. :limit="limit"
  10. :accept="fileAccept"
  11. :on-error="handleUploadError"
  12. :on-exceed="handleExceed"
  13. :on-success="handleUploadSuccess"
  14. :show-file-list="false"
  15. :headers="headers"
  16. class="upload-file-uploader"
  17. v-if="!disabled"
  18. >
  19. <!-- 上传按钮 -->
  20. <el-button type="primary">选取文件</el-button>
  21. </el-upload>
  22. <!-- 上传提示 -->
  23. <div v-if="showTip && !disabled" class="el-upload__tip">
  24. 请上传
  25. <template v-if="fileSize">
  26. 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
  27. </template>
  28. <template v-if="fileType">
  29. 格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
  30. </template>
  31. 的文件
  32. </div>
  33. <!-- 文件列表 -->
  34. <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
  35. <li v-for="(file, index) in fileList" :key="file.uid" class="el-upload-list__item ele-upload-list__item-content">
  36. <el-link :href="`${file.url}`" :underline="false" target="_blank">
  37. <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
  38. </el-link>
  39. <div class="ele-upload-list__item-content-action">
  40. <el-button type="danger" v-if="!disabled" link @click="handleDelete(index)">删除</el-button>
  41. </div>
  42. </li>
  43. </transition-group>
  44. </div>
  45. </template>
  46. <script setup lang="ts">
  47. import { propTypes } from '@/utils/propTypes';
  48. import { delOss, listByIds } from '@/api/system/oss';
  49. import { globalHeaders } from '@/utils/request';
  50. const props = defineProps({
  51. modelValue: {
  52. type: [String, Object, Array],
  53. default: () => []
  54. },
  55. // 数量限制
  56. limit: propTypes.number.def(5),
  57. // 大小限制(MB)
  58. fileSize: propTypes.number.def(5),
  59. // 文件类型, 例如['png', 'jpg', 'jpeg']
  60. fileType: propTypes.array.def(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf']),
  61. // 是否显示提示
  62. isShowTip: propTypes.bool.def(true),
  63. // 禁用组件(仅查看文件)
  64. disabled: propTypes.bool.def(false)
  65. });
  66. const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  67. const emit = defineEmits(['update:modelValue']);
  68. const number = ref(0);
  69. const uploadList = ref<any[]>([]);
  70. const baseUrl = import.meta.env.VITE_APP_BASE_API;
  71. const uploadFileUrl = ref(baseUrl + '/resource/oss/upload'); // 上传文件服务器地址
  72. const headers = ref(globalHeaders());
  73. const fileList = ref<any[]>([]);
  74. const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));
  75. const fileUploadRef = ref<ElUploadInstance>();
  76. // 监听 fileType 变化,更新 fileAccept
  77. const fileAccept = computed(() => props.fileType.map((type) => `.${type}`).join(','));
  78. watch(
  79. () => props.modelValue,
  80. async (val) => {
  81. if (val) {
  82. let temp = 1;
  83. // 首先将值转为数组
  84. let list: any[] = [];
  85. if (Array.isArray(val)) {
  86. list = val;
  87. } else {
  88. const res = await listByIds(val);
  89. list = res.data.map((oss) => {
  90. return {
  91. name: oss.originalName,
  92. url: oss.url,
  93. ossId: oss.ossId
  94. };
  95. });
  96. }
  97. // 然后将数组转为对象数组
  98. fileList.value = list.map((item) => {
  99. item = { name: item.name, url: item.url, ossId: item.ossId };
  100. item.uid = item.uid || new Date().getTime() + temp++;
  101. return item;
  102. });
  103. } else {
  104. fileList.value = [];
  105. return [];
  106. }
  107. },
  108. { deep: true, immediate: true }
  109. );
  110. // 上传前校检格式和大小
  111. const handleBeforeUpload = (file: any) => {
  112. // 校检文件类型
  113. if (props.fileType.length) {
  114. const fileName = file.name.split('.');
  115. const fileExt = fileName[fileName.length - 1];
  116. const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
  117. if (!isTypeOk) {
  118. proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`);
  119. return false;
  120. }
  121. }
  122. // 校检文件名是否包含特殊字符
  123. if (file.name.includes(',')) {
  124. proxy?.$modal.msgError('文件名不正确,不能包含英文逗号!');
  125. return false;
  126. }
  127. // 校检文件大小
  128. if (props.fileSize) {
  129. const isLt = file.size / 1024 / 1024 < props.fileSize;
  130. if (!isLt) {
  131. proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
  132. return false;
  133. }
  134. }
  135. proxy?.$modal.loading('正在上传文件,请稍候...');
  136. number.value++;
  137. return true;
  138. };
  139. // 文件个数超出
  140. const handleExceed = () => {
  141. proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  142. };
  143. // 上传失败
  144. const handleUploadError = () => {
  145. proxy?.$modal.msgError('上传文件失败');
  146. };
  147. // 上传成功回调
  148. const handleUploadSuccess = (res: any, file: UploadFile) => {
  149. if (res.code === 200) {
  150. uploadList.value.push({
  151. name: res.data.fileName,
  152. url: res.data.url,
  153. ossId: res.data.ossId
  154. });
  155. uploadedSuccessfully();
  156. } else {
  157. number.value--;
  158. proxy?.$modal.closeLoading();
  159. proxy?.$modal.msgError(res.msg);
  160. fileUploadRef.value?.handleRemove(file);
  161. uploadedSuccessfully();
  162. }
  163. };
  164. // 删除文件
  165. const handleDelete = (index: number) => {
  166. let ossId = fileList.value[index].ossId;
  167. delOss(ossId);
  168. fileList.value.splice(index, 1);
  169. emit('update:modelValue', listToString(fileList.value));
  170. };
  171. // 上传结束处理
  172. const uploadedSuccessfully = () => {
  173. if (number.value > 0 && uploadList.value.length === number.value) {
  174. fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
  175. uploadList.value = [];
  176. number.value = 0;
  177. emit('update:modelValue', listToString(fileList.value));
  178. proxy?.$modal.closeLoading();
  179. }
  180. };
  181. // 获取文件名称
  182. const getFileName = (name: string) => {
  183. // 如果是url那么取最后的名字 如果不是直接返回
  184. if (name.lastIndexOf('/') > -1) {
  185. return name.slice(name.lastIndexOf('/') + 1);
  186. } else {
  187. return name;
  188. }
  189. };
  190. // 对象转成指定字符串分隔
  191. const listToString = (list: any[], separator?: string) => {
  192. let strs = '';
  193. separator = separator || ',';
  194. list.forEach((item) => {
  195. if (item.ossId) {
  196. strs += item.ossId + separator;
  197. }
  198. });
  199. return strs != '' ? strs.substring(0, strs.length - 1) : '';
  200. };
  201. </script>
  202. <style lang="scss" scoped>
  203. .upload-file-uploader {
  204. margin-bottom: 5px;
  205. }
  206. .upload-file-list .el-upload-list__item {
  207. border: 1px solid #e4e7ed;
  208. line-height: 2;
  209. margin-bottom: 10px;
  210. position: relative;
  211. }
  212. .upload-file-list .ele-upload-list__item-content {
  213. display: flex;
  214. justify-content: space-between;
  215. align-items: center;
  216. color: inherit;
  217. }
  218. .ele-upload-list__item-content-action .el-link {
  219. margin-right: 10px;
  220. }
  221. </style>