sa-upload-image.global.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. <template>
  2. <div class="sa-upload-image">
  3. <div class="upload-container sa-flex sa-flex-wrap">
  4. <!-- 已上传的图片列表 -->
  5. <sa-draggable
  6. v-if="imageList.length > 0"
  7. v-model="imageList"
  8. :animation="300"
  9. handle=".sortable-drag"
  10. item-key="url"
  11. @end="handleSort"
  12. class="sa-flex sa-flex-wrap"
  13. >
  14. <template #item="{ element, index }">
  15. <div
  16. class="image-item mr-2px"
  17. :class="{ 'compact-mode': compact }"
  18. :style="{ width: size + 'px', height: size + 'px' }"
  19. >
  20. <el-image
  21. :src="element"
  22. fit="cover"
  23. :preview-src-list="compact ? [] : imageList"
  24. :initial-index="compact ? 0 : index"
  25. :preview-teleported="true"
  26. @click="compact ? previewImage(element, index) : null"
  27. :style="{ cursor: compact ? 'pointer' : 'default' }"
  28. >
  29. <template #error>
  30. <div class="image-error">
  31. <el-icon><Picture /></el-icon>
  32. </div>
  33. </template>
  34. </el-image>
  35. <div class="image-mask" :class="{ 'compact-mask': compact }">
  36. <template v-if="compact">
  37. <el-icon @click.stop="removeImage(index)" title="删除" size="12"
  38. ><Delete
  39. /></el-icon>
  40. </template>
  41. <template v-else>
  42. <el-icon class="sortable-drag" title="拖拽排序" size="24"><Rank /></el-icon>
  43. <el-icon @click="previewImage(element, index)" title="预览" size="24"
  44. ><ZoomIn
  45. /></el-icon>
  46. <el-icon @click="removeImage(index)" title="删除" size="24"><Delete /></el-icon>
  47. </template>
  48. </div>
  49. </div>
  50. </template>
  51. </sa-draggable>
  52. <!-- 上传按钮 -->
  53. <div
  54. v-if="!maxCount || imageList.length < maxCount"
  55. class="upload-wrapper"
  56. :style="{ width: size + 'px', height: size + 'px' }"
  57. >
  58. <div
  59. class="upload-trigger"
  60. :class="{ 'compact-trigger': compact, 'is-uploading': uploading }"
  61. :style="{ width: size + 'px', height: size + 'px' }"
  62. @click="handleUploadClick"
  63. >
  64. <el-icon class="upload-icon" :size="compact ? 16 : 24">
  65. <Plus />
  66. </el-icon>
  67. <div v-if="!compact" class="upload-text">{{ placeholder || '上传图片' }}</div>
  68. </div>
  69. <!-- 自定义loading遮罩 -->
  70. <div v-if="uploading" class="upload-loading">
  71. <div class="loading-spinner"></div>
  72. <div v-if="!compact" class="loading-text">上传中...</div>
  73. </div>
  74. </div>
  75. <!-- 隐藏的文件输入框 -->
  76. <input
  77. ref="fileInputRef"
  78. type="file"
  79. :accept="acceptString"
  80. :multiple="multiple"
  81. style="display: none"
  82. @change="handleFileSelect"
  83. />
  84. </div>
  85. <!-- 提示信息 -->
  86. <div v-if="showTip" class="upload-tip">
  87. <span v-if="maxCount">最多上传{{ maxCount }}张,</span>
  88. <span v-if="accept && accept.length">支持{{ accept.join('、') }}格式,</span>
  89. <span v-if="maxSize">单张图片不超过{{ maxSize }}MB</span>
  90. </div>
  91. <!-- 图片预览弹窗 -->
  92. <el-image-viewer
  93. v-if="previewVisible"
  94. :url-list="previewImageList"
  95. :initial-index="previewInitialIndex"
  96. :infinite="false"
  97. :hide-on-click-modal="true"
  98. :teleported="true"
  99. :z-index="3000"
  100. @close="closePreview"
  101. />
  102. </div>
  103. </template>
  104. <script>
  105. import { ref, computed, watch } from 'vue';
  106. import { ElMessage, ElImageViewer } from 'element-plus';
  107. import { Picture, Plus, Rank, ZoomIn, Delete } from '@element-plus/icons-vue';
  108. import SaDraggable from 'vuedraggable';
  109. import adminApi from '@/app/admin/api';
  110. export default {
  111. name: 'SaUploadImage',
  112. components: {
  113. Picture,
  114. Plus,
  115. Rank,
  116. ZoomIn,
  117. Delete,
  118. SaDraggable,
  119. ElImageViewer,
  120. },
  121. };
  122. </script>
  123. <script setup>
  124. const props = defineProps({
  125. modelValue: {
  126. type: Array,
  127. default: () => [],
  128. },
  129. // 是否直传,默认为true
  130. directUpload: {
  131. type: Boolean,
  132. default: true,
  133. },
  134. // 最大上传数量
  135. maxCount: {
  136. type: Number,
  137. default: 0,
  138. },
  139. // 支持的文件格式
  140. accept: {
  141. type: Array,
  142. default: () => ['jpg', 'jpeg', 'png'],
  143. },
  144. // 最大文件大小(MB)
  145. maxSize: {
  146. type: Number,
  147. default: 2,
  148. },
  149. // 是否支持多选
  150. multiple: {
  151. type: Boolean,
  152. default: true,
  153. },
  154. // 图片尺寸
  155. size: {
  156. type: Number,
  157. default: 100,
  158. },
  159. // 占位符文本
  160. placeholder: {
  161. type: String,
  162. default: '',
  163. },
  164. // 是否显示提示信息
  165. showTip: {
  166. type: Boolean,
  167. default: true,
  168. },
  169. // 精简模式
  170. compact: {
  171. type: Boolean,
  172. default: false,
  173. },
  174. });
  175. const emit = defineEmits(['update:modelValue', 'change']);
  176. // 文件输入框引用
  177. const fileInputRef = ref();
  178. // 图片列表
  179. const imageList = ref([...props.modelValue]);
  180. // 上传loading状态
  181. const uploading = ref(false);
  182. // 计算接受的文件类型字符串
  183. const acceptString = computed(() => {
  184. return props.accept.map((type) => `.${type}`).join(',');
  185. });
  186. // 添加一个标志来防止循环更新
  187. let isUpdatingFromProps = false;
  188. let isUpdatingFromInternal = false;
  189. // 数组比较函数
  190. const arraysEqual = (a, b) => {
  191. if (a.length !== b.length) return false;
  192. return a.every((val, index) => val === b[index]);
  193. };
  194. // 监听外部数据变化
  195. watch(
  196. () => props.modelValue,
  197. (newValue) => {
  198. if (isUpdatingFromInternal) return;
  199. const currentValue = imageList.value;
  200. if (!arraysEqual(newValue, currentValue)) {
  201. isUpdatingFromProps = true;
  202. imageList.value = [...newValue];
  203. setTimeout(() => {
  204. isUpdatingFromProps = false;
  205. }, 0);
  206. }
  207. },
  208. { deep: true },
  209. );
  210. // 监听内部数据变化
  211. watch(
  212. imageList,
  213. (newValue) => {
  214. if (isUpdatingFromProps) return;
  215. if (!arraysEqual(newValue, props.modelValue)) {
  216. isUpdatingFromInternal = true;
  217. emit('update:modelValue', [...newValue]);
  218. emit('change', [...newValue]);
  219. setTimeout(() => {
  220. isUpdatingFromInternal = false;
  221. }, 0);
  222. }
  223. },
  224. { deep: true },
  225. );
  226. // 处理上传点击
  227. const handleUpload = () => {
  228. if (props.directUpload) {
  229. // 直传模式,直接打开文件选择
  230. fileInputRef.value?.click();
  231. } else {
  232. // 非直传模式,打开文件管理弹窗
  233. openFileManager();
  234. }
  235. };
  236. // 处理点击事件(带上传状态检查)
  237. const handleUploadClick = () => {
  238. if (!uploading.value) {
  239. handleUpload();
  240. }
  241. };
  242. // 处理文件选择
  243. const handleFileSelect = async (event) => {
  244. const files = Array.from(event.target.files);
  245. if (!files.length) return;
  246. // 检查数量限制
  247. if (props.maxCount && imageList.value.length + files.length > props.maxCount) {
  248. ElMessage.warning(`最多只能上传${props.maxCount}张图片`);
  249. return;
  250. }
  251. // 验证文件
  252. const validFiles = [];
  253. for (const file of files) {
  254. if (validateFile(file)) {
  255. validFiles.push(file);
  256. }
  257. }
  258. if (validFiles.length === 0) return;
  259. // 开始上传,显示loading
  260. uploading.value = true;
  261. // 上传文件
  262. try {
  263. const uploadPromises = validFiles.map((file) => uploadFile(file));
  264. const results = await Promise.all(uploadPromises);
  265. // 添加成功上传的图片
  266. results.forEach((result) => {
  267. if (result.success) {
  268. imageList.value.push(result.url);
  269. }
  270. });
  271. const successCount = results.filter((r) => r.success).length;
  272. if (successCount > 0) {
  273. ElMessage.success(`成功上传${successCount}张图片`);
  274. }
  275. // 如果有失败的,显示失败信息
  276. const failedCount = results.length - successCount;
  277. if (failedCount > 0) {
  278. ElMessage.error(`${failedCount}张图片上传失败`);
  279. }
  280. } catch (error) {
  281. ElMessage.error('上传失败:' + error.message);
  282. } finally {
  283. // 无论成功还是失败,都关闭loading
  284. uploading.value = false;
  285. }
  286. // 清空文件输入框
  287. event.target.value = '';
  288. };
  289. // 验证文件
  290. const validateFile = (file) => {
  291. // 检查文件类型
  292. const fileExtension = file.name.split('.').pop().toLowerCase();
  293. if (!props.accept.includes(fileExtension)) {
  294. ElMessage.warning(`不支持${fileExtension}格式,请选择${props.accept.join('、')}格式的图片`);
  295. return false;
  296. }
  297. // 检查文件大小
  298. const fileSizeMB = file.size / 1024 / 1024;
  299. if (props.maxSize && fileSizeMB > props.maxSize) {
  300. ElMessage.warning(`图片大小不能超过${props.maxSize}MB`);
  301. return false;
  302. }
  303. return true;
  304. };
  305. // 上传文件
  306. const uploadFile = async (file) => {
  307. try {
  308. var formData = new FormData();
  309. formData.append('file', file);
  310. const response = await adminApi.file.upload({}, formData);
  311. if (response.code == '200') {
  312. return {
  313. success: true,
  314. url: response.data,
  315. };
  316. } else {
  317. throw new Error(response.msg || '上传失败');
  318. }
  319. } catch (error) {
  320. console.error('上传文件失败:', error);
  321. return {
  322. success: false,
  323. error: error.message,
  324. };
  325. }
  326. };
  327. // 打开文件管理器(非直传模式)
  328. const openFileManager = () => {
  329. // 这里可以集成现有的文件管理器组件
  330. console.log('打开文件管理器');
  331. ElMessage.info('文件管理器功能待实现');
  332. };
  333. // 图片预览状态
  334. const previewVisible = ref(false);
  335. const previewImageUrl = ref('');
  336. const previewImageList = ref([]);
  337. const previewInitialIndex = ref(0);
  338. // 预览图片
  339. const previewImage = (url, index = 0) => {
  340. previewImageUrl.value = url;
  341. previewImageList.value = [...imageList.value];
  342. previewInitialIndex.value = index;
  343. previewVisible.value = true;
  344. };
  345. // 关闭预览
  346. const closePreview = () => {
  347. previewVisible.value = false;
  348. previewImageUrl.value = '';
  349. previewImageList.value = [];
  350. previewInitialIndex.value = 0;
  351. };
  352. // 删除图片
  353. const removeImage = (index) => {
  354. imageList.value.splice(index, 1);
  355. };
  356. // 处理拖拽排序
  357. const handleSort = () => {
  358. // 拖拽排序后自动触发 watch 更新
  359. console.log('图片排序已更新');
  360. };
  361. </script>
  362. <style lang="scss" scoped>
  363. .sa-upload-image {
  364. .upload-container {
  365. gap: 8px;
  366. }
  367. .image-item {
  368. position: relative;
  369. border-radius: 6px;
  370. overflow: hidden;
  371. border: 1px solid #dcdfe6;
  372. .el-image {
  373. width: 100%;
  374. height: 100%;
  375. }
  376. .image-error {
  377. display: flex;
  378. align-items: center;
  379. justify-content: center;
  380. width: 100%;
  381. height: 100%;
  382. background: #f5f7fa;
  383. color: #909399;
  384. }
  385. .image-mask {
  386. position: absolute;
  387. top: 0;
  388. left: 0;
  389. right: 0;
  390. bottom: 0;
  391. background: rgba(0, 0, 0, 0.6);
  392. display: flex;
  393. align-items: center;
  394. justify-content: center;
  395. gap: 8px;
  396. opacity: 0;
  397. transition: opacity 0.3s;
  398. .el-icon {
  399. color: white;
  400. font-size: 16px;
  401. cursor: pointer;
  402. padding: 4px;
  403. border-radius: 2px;
  404. transition: background-color 0.3s;
  405. &:hover {
  406. background: rgba(255, 255, 255, 0.2);
  407. }
  408. &.sortable-drag {
  409. cursor: move;
  410. }
  411. }
  412. }
  413. &:hover .image-mask {
  414. opacity: 1;
  415. }
  416. }
  417. .upload-wrapper {
  418. position: relative;
  419. display: inline-block;
  420. }
  421. .upload-trigger {
  422. display: flex;
  423. flex-direction: column;
  424. align-items: center;
  425. justify-content: center;
  426. border: 2px dashed #dcdfe6;
  427. border-radius: 6px;
  428. cursor: pointer;
  429. transition: all 0.3s;
  430. background: #fafafa;
  431. &:hover:not(.is-uploading) {
  432. border-color: var(--el-color-primary);
  433. }
  434. &.is-uploading {
  435. cursor: not-allowed;
  436. border-color: var(--el-color-primary);
  437. border-style: solid;
  438. background: var(--el-color-primary-light-9);
  439. animation: uploadingBorder 2s ease-in-out infinite;
  440. }
  441. .upload-icon {
  442. font-size: 24px;
  443. color: #8c939d;
  444. margin-bottom: 4px;
  445. transition: all 0.3s;
  446. }
  447. .upload-text {
  448. font-size: 12px;
  449. color: #8c939d;
  450. transition: all 0.3s;
  451. }
  452. }
  453. .upload-loading {
  454. position: absolute;
  455. top: 0;
  456. left: 0;
  457. right: 0;
  458. bottom: 0;
  459. display: flex;
  460. flex-direction: column;
  461. align-items: center;
  462. justify-content: center;
  463. background: rgba(255, 255, 255, 0.9);
  464. border-radius: 6px;
  465. backdrop-filter: blur(2px);
  466. .loading-spinner {
  467. width: 20px;
  468. height: 20px;
  469. border: 2px solid #e4e7ed;
  470. border-top: 2px solid var(--el-color-primary);
  471. border-radius: 50%;
  472. animation: spin 1s linear infinite;
  473. margin-bottom: 8px;
  474. }
  475. .loading-text {
  476. font-size: 12px;
  477. color: var(--el-color-primary);
  478. font-weight: 500;
  479. }
  480. }
  481. @keyframes spin {
  482. 0% {
  483. transform: rotate(0deg);
  484. }
  485. 100% {
  486. transform: rotate(360deg);
  487. }
  488. }
  489. @keyframes uploadingBorder {
  490. 0% {
  491. border-color: var(--el-color-primary);
  492. box-shadow: 0 0 0 0 var(--el-color-primary-light-7);
  493. }
  494. 50% {
  495. border-color: var(--el-color-primary-light-3);
  496. box-shadow: 0 0 0 4px var(--el-color-primary-light-8);
  497. }
  498. 100% {
  499. border-color: var(--el-color-primary);
  500. box-shadow: 0 0 0 0 var(--el-color-primary-light-7);
  501. }
  502. }
  503. .upload-tip {
  504. margin-top: 8px;
  505. font-size: 12px;
  506. color: #909399;
  507. line-height: 1.4;
  508. }
  509. /* 精简模式样式 */
  510. .compact-mode {
  511. border: 1px solid #dcdfe6;
  512. border-radius: 4px;
  513. &:hover {
  514. border-color: var(--el-color-primary);
  515. }
  516. }
  517. .compact-mask {
  518. background: transparent;
  519. pointer-events: none;
  520. .el-icon {
  521. position: absolute;
  522. top: 2px;
  523. right: 2px;
  524. background: rgba(0, 0, 0, 0.8);
  525. border-radius: 50%;
  526. padding: 1px;
  527. pointer-events: auto;
  528. width: 16px;
  529. height: 16px;
  530. display: flex;
  531. align-items: center;
  532. justify-content: center;
  533. font-size: 12px;
  534. }
  535. }
  536. .compact-trigger {
  537. border: 1px dashed #dcdfe6;
  538. border-radius: 4px;
  539. background: #fafafa;
  540. transition: all 0.3s;
  541. &:hover {
  542. border-color: var(--el-color-primary);
  543. background: var(--el-color-primary-light-9);
  544. }
  545. .upload-icon {
  546. color: #8c939d;
  547. }
  548. &:hover .upload-icon {
  549. color: var(--el-color-primary);
  550. }
  551. }
  552. }
  553. </style>