Imgs.vue 16 KB

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