index.vue 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 { ComponentInternalInstance } from "vue";
  48. import { ElUpload, UploadFile } from "element-plus";
  49. const props = defineProps({
  50. modelValue: [String, Object, Array],
  51. // 数量限制
  52. limit: {
  53. type: Number,
  54. default: 5,
  55. },
  56. // 大小限制(MB)
  57. fileSize: {
  58. type: Number,
  59. default: 5,
  60. },
  61. // 文件类型, 例如['png', 'jpg', 'jpeg']
  62. fileType: {
  63. type: Array,
  64. default: () => ["doc", "xls", "ppt", "txt", "pdf"],
  65. },
  66. // 是否显示提示
  67. isShowTip: {
  68. type: Boolean,
  69. default: true
  70. }
  71. });
  72. const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  73. const emit = defineEmits(['update:modelValue']);
  74. const number = ref(0);
  75. const uploadList = ref<any[]>([]);
  76. const baseUrl = import.meta.env.VITE_APP_BASE_API;
  77. const uploadFileUrl = ref(baseUrl + "/resource/oss/upload"); // 上传文件服务器地址
  78. const headers = ref({ Authorization: "Bearer " + getToken() });
  79. const fileList = ref<any[]>([]);
  80. const showTip = computed(
  81. () => props.isShowTip && (props.fileType || props.fileSize)
  82. );
  83. const fileUploadRef = ref(ElUpload);
  84. watch(() => props.modelValue, async val => {
  85. if (val) {
  86. let temp = 1;
  87. // 首先将值转为数组
  88. let list = [];
  89. if (Array.isArray(val)) {
  90. list = val;
  91. } else {
  92. const res = await listByIds(val as string)
  93. list = res.data.map((oss) => {
  94. const data = { name: oss.originalName, url: oss.url, ossId: oss.ossId };
  95. return data;
  96. });
  97. }
  98. // 然后将数组转为对象数组
  99. fileList.value = list.map(item => {
  100. item = {name: item.name, url: item.url, ossId: item.ossId};
  101. item.uid = item.uid || new Date().getTime() + temp++;
  102. return item;
  103. });
  104. } else {
  105. fileList.value = [];
  106. return [];
  107. }
  108. },{ deep: true, immediate: true });
  109. // 上传前校检格式和大小
  110. const handleBeforeUpload = (file: any) => {
  111. // 校检文件类型
  112. if (props.fileType.length) {
  113. const fileName = file.name.split('.');
  114. const fileExt = fileName[fileName.length - 1];
  115. const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
  116. if (!isTypeOk) {
  117. proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
  118. return false;
  119. }
  120. }
  121. // 校检文件大小
  122. if (props.fileSize) {
  123. const isLt = file.size / 1024 / 1024 < props.fileSize;
  124. if (!isLt) {
  125. proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
  126. return false;
  127. }
  128. }
  129. proxy?.$modal.loading("正在上传文件,请稍候...");
  130. number.value++;
  131. return true;
  132. }
  133. // 文件个数超出
  134. const handleExceed = () => {
  135. proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  136. }
  137. // 上传失败
  138. const handleUploadError = () => {
  139. proxy?.$modal.msgError("上传文件失败");
  140. }
  141. // 上传成功回调
  142. const handleUploadSuccess = (res:any, file: UploadFile) => {
  143. if (res.code === 200) {
  144. uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
  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>