Imgs.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. <template>
  2. <div class="upload-box" :class="{ 'hide-upload-trigger': shouldHideUploadTrigger }">
  3. <el-upload
  4. v-model:file-list="_fileList"
  5. action="#"
  6. list-type="picture-card"
  7. :class="['upload', self_disabled ? 'disabled' : '', drag ? 'no-border' : '']"
  8. :multiple="true"
  9. :disabled="self_disabled"
  10. :limit="limit"
  11. :http-request="handleHttpUpload"
  12. :before-upload="beforeUpload"
  13. :on-exceed="handleExceed"
  14. :on-success="showSuccessNotification ? uploadSuccess : undefined"
  15. :on-error="uploadError"
  16. :on-change="handleFileListChange"
  17. :drag="drag"
  18. :accept="fileType.join(',')"
  19. >
  20. <div class="upload-empty">
  21. <slot name="empty">
  22. <el-icon><Plus /></el-icon>
  23. <!-- <span>请上传图片</span> -->
  24. </slot>
  25. </div>
  26. <template #file="{ file }">
  27. <video
  28. v-if="isVideoFile(file) && file.url"
  29. :src="file.url"
  30. :poster="(file as any).coverUrl || undefined"
  31. class="upload-image"
  32. muted
  33. preload="metadata"
  34. playsinline
  35. />
  36. <img
  37. v-else-if="file.url && file.uid !== undefined && !imageLoadError.has(file.uid)"
  38. :src="file.url"
  39. class="upload-image"
  40. @error="handleImageError"
  41. @load="handleImageLoad"
  42. />
  43. <div v-else class="upload-image-placeholder">
  44. <el-icon><Picture /></el-icon>
  45. <span>{{ isVideoFile(file) ? "视频预览" : "图片预览" }}</span>
  46. </div>
  47. <div class="upload-handle" @click.stop>
  48. <div class="handle-icon" @click="handlePictureCardPreview(file)">
  49. <el-icon><ZoomIn /></el-icon>
  50. <span>查看</span>
  51. </div>
  52. <div v-if="!self_disabled" class="handle-icon" @click="handleRemove(file)">
  53. <el-icon><Delete /></el-icon>
  54. <span>删除</span>
  55. </div>
  56. </div>
  57. </template>
  58. </el-upload>
  59. <div class="el-upload__tip">
  60. <slot name="tip" />
  61. </div>
  62. <el-image-viewer v-if="imgViewVisible" :url-list="[viewImageUrl]" @close="imgViewVisible = false" />
  63. </div>
  64. </template>
  65. <script setup lang="ts" name="UploadImgs">
  66. import { ref, computed, inject, watch, nextTick } from "vue";
  67. import { Plus, Picture } from "@element-plus/icons-vue";
  68. import { uploadImg } from "@/api/modules/upload";
  69. import type { UploadProps, UploadFile, UploadUserFile, UploadRequestOptions } from "element-plus";
  70. import { ElMessage, ElNotification, formContextKey, formItemContextKey } from "element-plus";
  71. import { useSimpleUploadOverlayStore } from "@/stores/modules/simpleUploadOverlay";
  72. interface UploadFileProps {
  73. fileList: UploadUserFile[];
  74. /** 上传 api;第二参为透传选项(如 skipSimpleUploadOverlay),与默认 uploadImg 一致 */
  75. api?: (params: FormData, options?: Record<string, unknown>) => Promise<any>;
  76. drag?: boolean; // 是否支持拖拽上传 ==> 非必传(默认为 true)
  77. disabled?: boolean; // 是否禁用上传组件 ==> 非必传(默认为 false)
  78. limit?: number; // 最大图片上传数 ==> 非必传(默认为 5张)
  79. fileSize?: number; // 图片大小限制 ==> 非必传(默认为 5M)
  80. fileType?: string[]; // 接受的 MIME(图片 + 可选视频)==> 非必传
  81. height?: string; // 组件高度 ==> 非必传(默认为 150px)
  82. width?: string; // 组件宽度 ==> 非必传(默认为 150px)
  83. borderRadius?: string; // 组件边框圆角 ==> 非必传(默认为 8px)
  84. onSuccess?: (url: string) => void;
  85. onVideoPreview?: (url: string) => void; // 点击视频「查看」时的回调,用于父级弹窗放大预览(不传则新标签页打开)
  86. showSuccessNotification?: boolean; // 是否显示上传成功通知 ==> 非必传(默认为 true)
  87. hideUploadTrigger?: boolean; // 是否隐藏上传入口(达限或自定义隐藏时使用)==> 非必传(默认为 false)
  88. }
  89. const props = withDefaults(defineProps<UploadFileProps>(), {
  90. fileList: () => [],
  91. drag: true,
  92. disabled: false,
  93. limit: 5,
  94. fileSize: 5,
  95. fileType: () => ["image/jpeg", "image/png", "image/gif", "video/mp4", "video/webm", "video/quicktime", "video/ogg"],
  96. height: "150px",
  97. width: "150px",
  98. borderRadius: "8px",
  99. showSuccessNotification: true,
  100. hideUploadTrigger: false
  101. });
  102. // 上传入口是否隐藏(达限或显式传入 hideUploadTrigger 时)
  103. const shouldHideUploadTrigger = computed(() => props.hideUploadTrigger || (props.fileList?.length ?? 0) >= props.limit);
  104. // 获取 el-form 组件上下文
  105. const formContext = inject(formContextKey, void 0);
  106. // 获取 el-form-item 组件上下文
  107. const formItemContext = inject(formItemContextKey, void 0);
  108. // 判断是否禁用上传和删除
  109. const self_disabled = computed(() => {
  110. return props.disabled || formContext?.disabled;
  111. });
  112. const _fileList = ref<UploadUserFile[]>(props.fileList);
  113. // 标记是否正在从 props 同步,避免循环更新
  114. let isSyncingFromProps = false;
  115. // 监听 props.fileList 列表默认值改变
  116. watch(
  117. () => props.fileList,
  118. (n: UploadUserFile[]) => {
  119. isSyncingFromProps = true;
  120. _fileList.value = n;
  121. nextTick(() => {
  122. isSyncingFromProps = false;
  123. });
  124. }
  125. );
  126. // 监听 _fileList 的变化,自动同步到父组件(排除从 props 同步的情况)
  127. // 注意:on-change 事件已经处理了大部分情况,这个 watch 作为备用
  128. watch(
  129. () => _fileList.value,
  130. (newList, oldList) => {
  131. if (!isSyncingFromProps && newList !== oldList) {
  132. // 延迟执行,避免与 on-change 重复
  133. nextTick(() => {
  134. if (!isSyncingFromProps) {
  135. emit("update:fileList", [...newList]);
  136. }
  137. });
  138. }
  139. },
  140. { deep: true, immediate: false }
  141. );
  142. // 记录正在上传的文件数量(使用 Set 跟踪文件 UID,更可靠)
  143. const uploadingFiles = new Set<string | number>();
  144. // 标记是否已经显示过成功提示,防止重复提示
  145. let hasShownSuccessNotification = false;
  146. /**
  147. * 多选时 el-upload 会对每个文件并发触发 http-request,易导致 /upload/simple 并发报错。
  148. * 通过 Promise 链串行化,同一时间只发起一次上传请求。
  149. */
  150. let sequentialUploadTail = Promise.resolve();
  151. /** 当前这一批(一次多选)里待上传的文件数;归零时关闭全局上传弹层 */
  152. let pendingBatchUploadCount = 0;
  153. let batchHadUploadError = false;
  154. function sleep(ms: number) {
  155. return new Promise<void>(resolve => setTimeout(resolve, ms));
  156. }
  157. async function finishBatchUploadOverlay() {
  158. const overlay = useSimpleUploadOverlayStore();
  159. if (batchHadUploadError) {
  160. overlay.dismiss();
  161. } else {
  162. overlay.bumpToComplete();
  163. await sleep(280);
  164. overlay.dismiss();
  165. if (props.showSuccessNotification) {
  166. ElMessage.success("上传成功");
  167. }
  168. }
  169. }
  170. // 记录图片加载失败的 UID
  171. const imageLoadError = ref<Set<string | number>>(new Set());
  172. /** 判断是否为视频文件(按 raw.type 或 url/name 后缀) */
  173. const isVideoFile = (file: UploadFile) => {
  174. const type = file.raw?.type;
  175. if (type && typeof type === "string" && type.startsWith("video/")) return true;
  176. const url = file.url || file.name || "";
  177. return /\.(mp4|webm|ogg|mov)(\?|$)/i.test(String(url));
  178. };
  179. /**
  180. * @description 文件上传之前判断
  181. * @param rawFile 选择的文件
  182. * */
  183. const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  184. const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;
  185. const acceptVideo = props.fileType.some(t => String(t).startsWith("video/"));
  186. const byNameVideo = /\.(mp4|m4v|webm|ogg|mov)(\?.*)?$/i.test(rawFile.name || "");
  187. const mimeVideo = typeof rawFile.type === "string" && rawFile.type.startsWith("video/");
  188. const looseVideoMime =
  189. acceptVideo && byNameVideo && (!rawFile.type || rawFile.type === "application/octet-stream" || mimeVideo);
  190. const typeListed = props.fileType.includes(rawFile.type);
  191. const okType = typeListed || looseVideoMime;
  192. if (!okType)
  193. ElNotification({
  194. title: "温馨提示",
  195. message: "上传文件不符合所需的格式!",
  196. type: "warning"
  197. });
  198. if (!imgSize)
  199. setTimeout(() => {
  200. ElNotification({
  201. title: "温馨提示",
  202. message: `上传文件大小不能超过 ${props.fileSize}M!`,
  203. type: "warning"
  204. });
  205. }, 0);
  206. return okType && imgSize;
  207. };
  208. /**
  209. * @description 图片上传
  210. * @param options upload 所有配置项
  211. * */
  212. const handleHttpUpload = (options: UploadRequestOptions): Promise<unknown> => {
  213. const fileUid = options.file.uid;
  214. if (uploadingFiles.size === 0) {
  215. hasShownSuccessNotification = false;
  216. }
  217. uploadingFiles.add(fileUid);
  218. if (pendingBatchUploadCount === 0) {
  219. batchHadUploadError = false;
  220. }
  221. pendingBatchUploadCount++;
  222. if (pendingBatchUploadCount === 1) {
  223. useSimpleUploadOverlayStore().beginUpload();
  224. }
  225. const runOne = async (): Promise<void> => {
  226. const formData = new FormData();
  227. formData.append("file", options.file);
  228. const simpleOpts = { skipSimpleUploadOverlay: true as const };
  229. try {
  230. const response = props.api ? await props.api(formData, simpleOpts) : await uploadImg(formData, simpleOpts);
  231. const fileUrl = response?.fileUrl || response?.data?.fileUrl || "";
  232. if (fileUrl) {
  233. const coverUrlRaw =
  234. (response as any)?.coverUrl ?? (response as any)?.data?.coverUrl ?? (response as any)?.data?.cover ?? "";
  235. const coverUrl = typeof coverUrlRaw === "string" && coverUrlRaw.trim() ? coverUrlRaw.trim() : "";
  236. (options.file as unknown as UploadFile).url = fileUrl;
  237. (options.file as unknown as UploadFile).status = "success";
  238. (options.file as unknown as UploadFile).response = response;
  239. if (coverUrl) {
  240. (options.file as any).coverUrl = coverUrl;
  241. }
  242. const fileIndex = _fileList.value.findIndex(item => item.uid === fileUid);
  243. if (fileIndex !== -1) {
  244. _fileList.value[fileIndex].url = fileUrl;
  245. _fileList.value[fileIndex].status = "success";
  246. (_fileList.value[fileIndex] as any).response = response;
  247. if (coverUrl) {
  248. (_fileList.value[fileIndex] as any).coverUrl = coverUrl;
  249. }
  250. }
  251. }
  252. options.onSuccess(response);
  253. emit("update:fileList", _fileList.value);
  254. if (props.onSuccess) {
  255. try {
  256. const result = props.onSuccess(fileUrl);
  257. if (
  258. result !== undefined &&
  259. result !== null &&
  260. typeof result === "object" &&
  261. typeof (result as any).then === "function"
  262. ) {
  263. (result as Promise<any>).catch((callbackError: any) => {
  264. console.error("onSuccess callback error:", callbackError);
  265. });
  266. }
  267. } catch (callbackError) {
  268. console.error("onSuccess callback error:", callbackError);
  269. }
  270. }
  271. } catch (error) {
  272. batchHadUploadError = true;
  273. uploadingFiles.delete(fileUid);
  274. options.onError(error as any);
  275. throw error;
  276. } finally {
  277. pendingBatchUploadCount--;
  278. if (pendingBatchUploadCount === 0) {
  279. await finishBatchUploadOverlay();
  280. }
  281. }
  282. };
  283. const p = sequentialUploadTail.then(runOne);
  284. sequentialUploadTail = p.catch(() => {
  285. /* 保持队列继续,不因单张失败阻断后续文件 */
  286. });
  287. return p;
  288. };
  289. /**
  290. * @description 图片上传成功
  291. * @param response 上传响应结果
  292. * @param uploadFile 上传的文件
  293. * */
  294. const emit = defineEmits<{
  295. "update:fileList": [value: UploadUserFile[]];
  296. }>();
  297. const uploadSuccess = (response: { fileUrl: string } | string | string[] | undefined, uploadFile: UploadFile) => {
  298. // 移除已完成的上传文件
  299. uploadingFiles.delete(uploadFile.uid);
  300. // 处理响应数据
  301. if (response) {
  302. if (typeof response === "string") {
  303. uploadFile.url = response;
  304. } else if (Array.isArray(response)) {
  305. uploadFile.url = response[0];
  306. } else if (response.fileUrl) {
  307. uploadFile.url = response.fileUrl;
  308. } else {
  309. // 如果 response 是对象但没有 fileUrl,尝试使用第一个属性值
  310. const values = Object.values(response);
  311. uploadFile.url = values[0] as string;
  312. }
  313. emit("update:fileList", _fileList.value);
  314. // 调用 el-form 内部的校验方法(可自动校验)
  315. formItemContext?.prop && formContext?.validateField([formItemContext.prop as string]);
  316. }
  317. // 当所有文件上传完成时,显示成功提示(只显示一次)
  318. if (uploadingFiles.size === 0 && !hasShownSuccessNotification) {
  319. hasShownSuccessNotification = true;
  320. // 判断是否为视频文件,显示相应的提示语
  321. const isVideo = isVideoFile(uploadFile);
  322. // ElNotification({
  323. // title: "温馨提示",
  324. // message: isVideo ? "视频上传成功!" : "图片上传成功!1111",
  325. // type: "success"
  326. // });
  327. }
  328. };
  329. /**
  330. * @description 文件列表变化处理
  331. * @param uploadFile 变化的文件
  332. * @param uploadFiles 当前文件列表
  333. */
  334. const handleFileListChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  335. // 当文件列表变化时,同步到父组件
  336. if (!isSyncingFromProps) {
  337. emit("update:fileList", uploadFiles as UploadUserFile[]);
  338. }
  339. };
  340. /**
  341. * @description 删除图片
  342. * @param file 删除的文件
  343. * */
  344. const handleRemove = (file: UploadFile) => {
  345. _fileList.value = _fileList.value.filter(item => item.url !== file.url || item.name !== file.name);
  346. emit("update:fileList", _fileList.value);
  347. // 移除时清除错误状态
  348. imageLoadError.value.delete(file.uid);
  349. };
  350. /**
  351. * @description 图片加载错误处理
  352. * */
  353. const handleImageError = (event: Event) => {
  354. const img = event.target as HTMLImageElement;
  355. // 通过查找对应的文件来获取 UID
  356. const file = _fileList.value.find(f => f.url === img.src);
  357. if (file && file.uid !== undefined) {
  358. imageLoadError.value.add(file.uid);
  359. }
  360. };
  361. /**
  362. * @description 图片加载成功处理
  363. * */
  364. const handleImageLoad = (event: Event) => {
  365. const img = event.target as HTMLImageElement;
  366. const file = _fileList.value.find(f => f.url === img.src);
  367. if (file && file.uid !== undefined) {
  368. imageLoadError.value.delete(file.uid);
  369. }
  370. };
  371. /**
  372. * @description 图片上传错误
  373. * */
  374. const uploadError = () => {
  375. // ElNotification({
  376. // title: "温馨提示",
  377. // message: "上传失败,请您重新上传!",
  378. // type: "error"
  379. // });
  380. };
  381. /**
  382. * @description 文件数超出
  383. * */
  384. const handleExceed = () => {
  385. ElNotification({
  386. title: "温馨提示",
  387. message: `当前最多只能上传 ${props.limit} 个文件,请移除后上传!`,
  388. type: "warning"
  389. });
  390. };
  391. /**
  392. * @description 图片预览
  393. * @param file 预览的文件
  394. * */
  395. const viewImageUrl = ref("");
  396. const imgViewVisible = ref(false);
  397. const handlePictureCardPreview: UploadProps["onPreview"] = file => {
  398. if (!file.url) return;
  399. if (isVideoFile(file)) {
  400. if (props.onVideoPreview) {
  401. props.onVideoPreview(file.url);
  402. } else {
  403. window.open(file.url, "_blank");
  404. }
  405. return;
  406. }
  407. viewImageUrl.value = file.url;
  408. imgViewVisible.value = true;
  409. };
  410. </script>
  411. <style scoped lang="scss">
  412. .is-error {
  413. .upload {
  414. :deep(.el-upload--picture-card),
  415. :deep(.el-upload-dragger) {
  416. border: 1px dashed var(--el-color-danger) !important;
  417. &:hover {
  418. border-color: var(--el-color-primary) !important;
  419. }
  420. }
  421. }
  422. }
  423. :deep(.disabled) {
  424. .el-upload--picture-card,
  425. .el-upload-dragger {
  426. cursor: not-allowed;
  427. background: var(--el-disabled-bg-color) !important;
  428. border: 1px dashed var(--el-border-color-darker);
  429. &:hover {
  430. border-color: var(--el-border-color-darker) !important;
  431. }
  432. }
  433. }
  434. .upload-box {
  435. .no-border {
  436. :deep(.el-upload--picture-card) {
  437. border: none !important;
  438. }
  439. }
  440. :deep(.upload) {
  441. .el-upload-dragger {
  442. display: flex;
  443. align-items: center;
  444. justify-content: center;
  445. width: 100%;
  446. height: 100%;
  447. padding: 0;
  448. overflow: hidden;
  449. border: 1px dashed var(--el-border-color-darker);
  450. border-radius: v-bind(borderRadius);
  451. &:hover {
  452. border: 1px dashed var(--el-color-primary);
  453. }
  454. }
  455. .el-upload-dragger.is-dragover {
  456. background-color: var(--el-color-primary-light-9);
  457. border: 2px dashed var(--el-color-primary) !important;
  458. }
  459. .el-upload-list__item,
  460. .el-upload--picture-card {
  461. width: v-bind(width);
  462. height: v-bind(height);
  463. background-color: transparent;
  464. border-radius: v-bind(borderRadius);
  465. }
  466. .upload-image {
  467. width: 100%;
  468. height: 100%;
  469. object-fit: contain;
  470. }
  471. .upload-image-placeholder {
  472. display: flex;
  473. flex-direction: column;
  474. align-items: center;
  475. justify-content: center;
  476. width: 100%;
  477. height: 100%;
  478. color: var(--el-text-color-secondary);
  479. background-color: var(--el-fill-color-lighter);
  480. .el-icon {
  481. margin-bottom: 8px;
  482. font-size: 32px;
  483. }
  484. span {
  485. font-size: 12px;
  486. }
  487. }
  488. .upload-handle {
  489. position: absolute;
  490. top: 0;
  491. right: 0;
  492. box-sizing: border-box;
  493. display: flex;
  494. align-items: center;
  495. justify-content: center;
  496. width: 100%;
  497. height: 100%;
  498. cursor: pointer;
  499. background: rgb(0 0 0 / 60%);
  500. opacity: 0;
  501. transition: var(--el-transition-duration-fast);
  502. .handle-icon {
  503. display: flex;
  504. flex-direction: column;
  505. align-items: center;
  506. justify-content: center;
  507. padding: 0 6%;
  508. color: aliceblue;
  509. .el-icon {
  510. margin-bottom: 15%;
  511. font-size: 140%;
  512. }
  513. span {
  514. font-size: 100%;
  515. }
  516. }
  517. }
  518. .el-upload-list__item {
  519. &:hover {
  520. .upload-handle {
  521. opacity: 1;
  522. }
  523. }
  524. }
  525. .upload-empty {
  526. display: flex;
  527. flex-direction: column;
  528. align-items: center;
  529. font-size: 12px;
  530. line-height: 30px;
  531. color: var(--el-color-info);
  532. .el-icon {
  533. font-size: 28px;
  534. color: var(--el-text-color-secondary);
  535. }
  536. }
  537. }
  538. .el-upload__tip {
  539. line-height: 15px;
  540. text-align: center;
  541. }
  542. /* 隐藏上传入口(达限或 hideUploadTrigger 为 true 时),隐藏包含 Plus 图标的触发区域 */
  543. &.hide-upload-trigger :deep(.el-upload:has(.upload-empty)) {
  544. display: none;
  545. }
  546. }
  547. </style>