Imgs.vue 18 KB

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