index.vue 6.4 KB

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