index.vue 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. <template>
  2. <div class="file-upload-container">
  3. <a-upload
  4. :file-list="fileList"
  5. :action="uploadFileUrl"
  6. :headers="headers"
  7. :before-upload="handleBeforeUpload"
  8. :remove="handleDelete"
  9. :multiple="true"
  10. :data="data"
  11. :disabled="disabled"
  12. :show-upload-list="true"
  13. @change="handleChange"
  14. >
  15. <a-button v-if="!disabled && (fileList.length < limit || limit === 0)" type="primary" :loading="uploading">
  16. <upload-outlined /> 选择文件
  17. </a-button>
  18. <template #itemRender="{ file }">
  19. <div class="file-item">
  20. <a-space>
  21. <file-outlined />
  22. <a :href="`${baseUrl}${file.url || file.response?.fileName}`" target="_blank">
  23. {{ getFileName(file.name || file.response?.fileName) }}
  24. </a>
  25. </a-space>
  26. </div>
  27. </template>
  28. </a-upload>
  29. <!-- 上传提示 -->
  30. <div class="upload-tip" v-if="showTip">
  31. 请上传
  32. <template v-if="fileSize"> 大小不超过 <b style="color: #ff4d4f">{{ fileSize }}MB</b> </template>
  33. <template v-if="fileType"> 格式为 <b style="color: #ff4d4f">{{ fileType.join("/") }}</b> </template>
  34. 的文件
  35. </div>
  36. </div>
  37. </template>
  38. <script>
  39. import { defineComponent, ref, watch, computed, nextTick } from 'vue';
  40. import { message } from 'ant-design-vue';
  41. import { UploadOutlined, FileOutlined } from '@ant-design/icons-vue';
  42. import { getToken } from "@/utils/auth";
  43. import Sortable from 'sortablejs';
  44. export default defineComponent({
  45. name: "FileUpload",
  46. components: {
  47. UploadOutlined,
  48. FileOutlined
  49. },
  50. props: {
  51. // 值
  52. modelValue: {
  53. type: [String, Object, Array],
  54. default: ''
  55. },
  56. // 上传接口地址
  57. action: {
  58. type: String,
  59. default: "/common/upload"
  60. },
  61. // 上传携带的参数
  62. data: {
  63. type: Object,
  64. default: () => ({})
  65. },
  66. // 数量限制
  67. limit: {
  68. type: Number,
  69. default: 5
  70. },
  71. // 大小限制(MB)
  72. fileSize: {
  73. type: Number,
  74. default: 5
  75. },
  76. // 文件类型, 例如['png', 'jpg', 'jpeg']
  77. fileType: {
  78. type: Array,
  79. default: () => ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "pdf"]
  80. },
  81. // 是否显示提示
  82. isShowTip: {
  83. type: Boolean,
  84. default: true
  85. },
  86. // 禁用组件(仅查看文件)
  87. disabled: {
  88. type: Boolean,
  89. default: false
  90. },
  91. // 拖动排序
  92. drag: {
  93. type: Boolean,
  94. default: true
  95. }
  96. },
  97. emits: ['update:modelValue'],
  98. setup(props, { emit }) {
  99. const fileList = ref([]);
  100. const uploading = ref(false);
  101. const uploadListRef = ref(null);
  102. const baseUrl = import.meta.env.VITE_APP_BASE_API || '';
  103. const uploadFileUrl = computed(() => baseUrl + props.action);
  104. const headers = {
  105. Authorization: "Bearer " + getToken(),
  106. };
  107. // 是否显示提示
  108. const showTip = computed(() => {
  109. return props.isShowTip && (props.fileType.length > 0 || props.fileSize > 0);
  110. });
  111. // 监听值变化
  112. watch(() => props.modelValue, (val) => {
  113. if (val) {
  114. let list = [];
  115. // 首先将值转为数组
  116. const values = Array.isArray(val) ? val : val.split(',');
  117. // 然后将数组转为对象数组
  118. list = values.map((item, index) => {
  119. if (typeof item === "string") {
  120. return {
  121. uid: `-${index}`,
  122. name: getFileName(item),
  123. status: 'done',
  124. url: item
  125. };
  126. }
  127. return item;
  128. });
  129. fileList.value = list;
  130. } else {
  131. fileList.value = [];
  132. }
  133. }, { deep: true, immediate: true });
  134. // 初始化拖拽排序
  135. const initSortable = () => {
  136. if (props.drag && !props.disabled) {
  137. nextTick(() => {
  138. // 使用延时确保DOM已经渲染完成
  139. setTimeout(() => {
  140. const el = document.querySelector('.ant-upload-list');
  141. if (el) {
  142. Sortable.create(el, {
  143. ghostClass: 'file-upload-ghost',
  144. onEnd: (evt) => {
  145. const targetIndex = evt.newIndex;
  146. const currentIndex = evt.oldIndex;
  147. if (targetIndex !== currentIndex) {
  148. const currentItem = fileList.value.splice(currentIndex, 1)[0];
  149. fileList.value.splice(targetIndex, 0, currentItem);
  150. updateModelValue();
  151. }
  152. }
  153. });
  154. }
  155. }, 200);
  156. });
  157. }
  158. };
  159. // 上传前校检格式和大小
  160. const handleBeforeUpload = (file) => {
  161. // 校检文件类型
  162. if (props.fileType && props.fileType.length > 0) {
  163. const fileName = file.name.split('.');
  164. const fileExt = fileName[fileName.length - 1].toLowerCase();
  165. const isTypeOk = props.fileType.map(type => type.toLowerCase()).indexOf(fileExt) >= 0;
  166. if (!isTypeOk) {
  167. message.error(`文件格式不正确,请上传${props.fileType.join("/")}格式文件!`);
  168. return false;
  169. }
  170. }
  171. // 校检文件名是否包含特殊字符
  172. if (file.name.includes(',')) {
  173. message.error('文件名不正确,不能包含英文逗号!');
  174. return false;
  175. }
  176. // 校检文件大小
  177. if (props.fileSize) {
  178. const isLt = file.size / 1024 / 1024 < props.fileSize;
  179. if (!isLt) {
  180. message.error(`上传文件大小不能超过 ${props.fileSize} MB!`);
  181. return false;
  182. }
  183. }
  184. uploading.value = true;
  185. return true;
  186. };
  187. // 处理上传状态变化
  188. const handleChange = (info) => {
  189. if (info.file.status === 'uploading') {
  190. uploading.value = true;
  191. } else if (info.file.status === 'done') {
  192. uploading.value = false;
  193. if (info.file.response && info.file.response.code === 200) {
  194. message.success(`${info.file.name} 上传成功`);
  195. updateModelValue();
  196. } else {
  197. message.error(info.file.response?.msg || `${info.file.name} 上传失败`);
  198. }
  199. } else if (info.file.status === 'error') {
  200. uploading.value = false;
  201. message.error(`${info.file.name} 上传失败`);
  202. } else if (info.file.status === 'removed') {
  203. updateModelValue();
  204. }
  205. };
  206. // 删除文件
  207. const handleDelete = (file) => {
  208. const index = fileList.value.findIndex(item => item.uid === file.uid);
  209. if (index !== -1) {
  210. fileList.value.splice(index, 1);
  211. updateModelValue();
  212. }
  213. return true;
  214. };
  215. // 更新表单值
  216. const updateModelValue = () => {
  217. const urls = fileList.value.map(file => {
  218. if (file.response && file.response.fileName) {
  219. return file.response.fileName;
  220. }
  221. return file.url || '';
  222. }).filter(url => url).join(',');
  223. emit('update:modelValue', urls);
  224. };
  225. // 获取文件名称
  226. const getFileName = (name) => {
  227. if (!name) return '';
  228. // 如果是url那么取最后的名字 如果不是直接返回
  229. if (name.lastIndexOf("/") > -1) {
  230. return name.slice(name.lastIndexOf("/") + 1);
  231. } else {
  232. return name;
  233. }
  234. };
  235. // 组件挂载后初始化拖拽
  236. nextTick(() => {
  237. initSortable();
  238. });
  239. return {
  240. fileList,
  241. uploading,
  242. uploadListRef,
  243. baseUrl,
  244. uploadFileUrl,
  245. headers,
  246. showTip,
  247. handleBeforeUpload,
  248. handleChange,
  249. handleDelete,
  250. getFileName
  251. };
  252. }
  253. });
  254. </script>
  255. <style scoped lang="less">
  256. .file-upload-container {
  257. .file-item {
  258. display: flex;
  259. align-items: center;
  260. }
  261. .upload-tip {
  262. margin-top: 8px;
  263. font-size: 12px;
  264. color: #606266;
  265. }
  266. :deep(.ant-upload-list-item) {
  267. transition: all 0.3s;
  268. }
  269. :deep(.file-upload-ghost) {
  270. opacity: 0.5;
  271. background: #e6f7ff;
  272. border: 1px dashed #1890ff;
  273. }
  274. }
  275. </style>