index.vue 6.6 KB

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