Imgs.vue 13 KB

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