index.vue 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. <template>
  2. <div class="upload-file">
  3. <el-upload
  4. ref="fileUpload"
  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">{{ btnText }}</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
  33. class="upload-file-list el-upload-list el-upload-list--text"
  34. name="el-fade-in-linear"
  35. tag="ul"
  36. v-if="showFileList"
  37. >
  38. <li
  39. v-for="(file, index) in fileList"
  40. :key="file.uid"
  41. class="el-upload-list__item ele-upload-list__item-content"
  42. >
  43. <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
  44. <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
  45. </el-link>
  46. <div class="ele-upload-list__item-content-action">
  47. <el-link :underline="false" type="danger" @click="handleDelete(index)">删除</el-link>
  48. </div>
  49. </li>
  50. </transition-group> -->
  51. </div>
  52. </template>
  53. <script setup lang="ts">
  54. import { getToken } from '@/utils/auth';
  55. import { ElMessage } from 'element-plus';
  56. import { getCurrentInstance, ComponentInternalInstance, ref, computed, watch } from 'vue';
  57. const props = defineProps({
  58. modelValue: [String, Object, Array] as any,
  59. // 数量限制
  60. limit: {
  61. type: Number,
  62. default: 5,
  63. },
  64. // 大小限制(MB)
  65. fileSize: {
  66. type: Number,
  67. default: 5,
  68. },
  69. // 文件类型, 例如['png', 'jpg', 'jpeg']
  70. fileType: {
  71. type: Array as () => Array<any>,
  72. default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf'],
  73. },
  74. // 是否显示提示
  75. isShowTip: {
  76. type: Boolean,
  77. default: true,
  78. },
  79. action: {
  80. type: String,
  81. default: 'business/common/upload',
  82. },
  83. // 按钮文字
  84. btnText: {
  85. type: String,
  86. default: '点击上传文件',
  87. },
  88. // 文件列表是否显示
  89. showFileList: {
  90. type: Boolean,
  91. default: true,
  92. },
  93. });
  94. const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  95. const emit = defineEmits(['update:modelValue', 'handleSuccess']);
  96. const number = ref(0);
  97. const uploadList = ref<any[]>([]);
  98. const baseUrl = import.meta.env.VITE_APP_BASE_API;
  99. const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + props.action); // 上传文件服务器地址
  100. const headers = ref({ Authorization: 'Bearer ' + getToken() });
  101. const fileList = ref<any[]>([]);
  102. const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));
  103. watch(
  104. () => props.modelValue,
  105. val => {
  106. if (val) {
  107. let temp = 1;
  108. // 首先将值转为数组
  109. const list = Array.isArray(val) ? val : props.modelValue!.split(',');
  110. // 然后将数组转为对象数组
  111. fileList.value = list.map((item: any) => {
  112. if (typeof item === 'string') {
  113. item = { name: item, url: item };
  114. }
  115. item.uid = item.uid || new Date().getTime() + temp++;
  116. return item;
  117. });
  118. } else {
  119. fileList.value = [];
  120. return [];
  121. }
  122. },
  123. { deep: true, immediate: true }
  124. );
  125. // 上传前校检格式和大小
  126. function handleBeforeUpload(file: any) {
  127. // 校检文件类型
  128. if (props.fileType.length) {
  129. const fileName = file.name.split('.');
  130. const fileExt = fileName[fileName.length - 1];
  131. const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
  132. if (!isTypeOk) {
  133. proxy!.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`);
  134. return false;
  135. }
  136. }
  137. // 校检文件大小
  138. if (props.fileSize) {
  139. const isLt = file.size / 1024 / 1024 < props.fileSize;
  140. if (!isLt) {
  141. proxy!.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
  142. return false;
  143. }
  144. }
  145. proxy!.$modal.loading('正在上传文件,请稍候...');
  146. number.value++;
  147. return true;
  148. }
  149. // 文件个数超出
  150. function handleExceed() {
  151. proxy!.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  152. }
  153. // 上传失败
  154. function handleUploadError(err: any) {
  155. proxy!.$modal.msgError('上传文件失败');
  156. proxy!.$modal.closeLoading();
  157. }
  158. // 上传成功回调
  159. function handleUploadSuccess(res: any, file: any) {
  160. if (res.code === 200) {
  161. uploadList.value.push({ name: res.fileName, url: res.fileName });
  162. uploadedSuccessfully();
  163. emit('handleSuccess', res);
  164. ElMessage.success(res.msg || '上传成功');
  165. } else {
  166. number.value--;
  167. proxy!.$modal.closeLoading();
  168. proxy!.$modal.msgError(res.msg);
  169. (proxy!.$refs.fileUpload as any).handleRemove(file);
  170. uploadedSuccessfully();
  171. }
  172. }
  173. // 清空列表
  174. function clearList() {
  175. (proxy!.$refs.fileUpload as any).clearFiles();
  176. }
  177. // 删除文件
  178. function handleDelete(index: any) {
  179. fileList.value.splice(index, 1);
  180. emit('update:modelValue', listToString(fileList.value));
  181. }
  182. // 上传结束处理
  183. function uploadedSuccessfully() {
  184. if (number.value > 0 && uploadList.value.length === number.value) {
  185. fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
  186. uploadList.value = [];
  187. number.value = 0;
  188. emit('update:modelValue', listToString(fileList.value));
  189. proxy!.$modal.closeLoading();
  190. }
  191. }
  192. // 获取文件名称
  193. function getFileName(name: any) {
  194. if (name.lastIndexOf('/') > -1) {
  195. return name.slice(name.lastIndexOf('/') + 1);
  196. } else {
  197. return '';
  198. }
  199. }
  200. // 对象转成指定字符串分隔
  201. function listToString(list: any, separator?: any) {
  202. let strs = '';
  203. separator = separator || ',';
  204. for (let i in list) {
  205. if (list[i].url) {
  206. strs += list[i].url + separator;
  207. }
  208. }
  209. return strs !== '' ? strs.substr(0, strs.length - 1) : '';
  210. }
  211. defineExpose({
  212. handleClea: clearList,
  213. });
  214. </script>
  215. <style scoped lang="scss">
  216. .upload-file-uploader {
  217. margin-bottom: 5px;
  218. }
  219. .upload-file-list .el-upload-list__item {
  220. border: 1px solid #e4e7ed;
  221. line-height: 2;
  222. margin-bottom: 10px;
  223. position: relative;
  224. }
  225. .upload-file-list .ele-upload-list__item-content {
  226. display: flex;
  227. justify-content: space-between;
  228. align-items: center;
  229. color: inherit;
  230. }
  231. .ele-upload-list__item-content-action .el-link {
  232. margin-right: 10px;
  233. }
  234. </style>