sa-upload-image.global.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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"
  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-trigger"
  56. :class="{ 'compact-trigger': compact }"
  57. :style="{ width: size + 'px', height: size + 'px' }"
  58. @click="handleUpload"
  59. >
  60. <el-icon class="upload-icon" :size="compact ? 16 : 24"><Plus /></el-icon>
  61. <div v-if="!compact" class="upload-text">{{ placeholder || '上传图片' }}</div>
  62. </div>
  63. <!-- 隐藏的文件输入框 -->
  64. <input
  65. ref="fileInputRef"
  66. type="file"
  67. :accept="acceptString"
  68. :multiple="multiple"
  69. style="display: none"
  70. @change="handleFileSelect"
  71. />
  72. </div>
  73. <!-- 提示信息 -->
  74. <div v-if="showTip" class="upload-tip">
  75. <span v-if="maxCount">最多上传{{ maxCount }}张,</span>
  76. <span v-if="accept && accept.length">支持{{ accept.join('、') }}格式,</span>
  77. <span v-if="maxSize">单张图片不超过{{ maxSize }}MB</span>
  78. </div>
  79. <!-- 图片预览弹窗 -->
  80. <el-image-viewer
  81. v-if="previewVisible"
  82. :url-list="previewImageList"
  83. :initial-index="previewInitialIndex"
  84. :infinite="false"
  85. :hide-on-click-modal="true"
  86. :teleported="true"
  87. :z-index="3000"
  88. @close="closePreview"
  89. />
  90. </div>
  91. </template>
  92. <script>
  93. import { ref, computed, watch } from 'vue';
  94. import { ElMessage, ElImageViewer } from 'element-plus';
  95. import { Picture, Plus, Rank, ZoomIn, Delete } from '@element-plus/icons-vue';
  96. import SaDraggable from 'vuedraggable';
  97. import adminApi from '@/app/admin/api';
  98. export default {
  99. name: 'SaUploadImage',
  100. components: {
  101. Picture,
  102. Plus,
  103. Rank,
  104. ZoomIn,
  105. Delete,
  106. SaDraggable,
  107. ElImageViewer,
  108. },
  109. };
  110. </script>
  111. <script setup>
  112. const props = defineProps({
  113. modelValue: {
  114. type: Array,
  115. default: () => [],
  116. },
  117. // 是否直传,默认为true
  118. directUpload: {
  119. type: Boolean,
  120. default: true,
  121. },
  122. // 最大上传数量
  123. maxCount: {
  124. type: Number,
  125. default: 0,
  126. },
  127. // 支持的文件格式
  128. accept: {
  129. type: Array,
  130. default: () => ['jpg', 'jpeg', 'png'],
  131. },
  132. // 最大文件大小(MB)
  133. maxSize: {
  134. type: Number,
  135. default: 2,
  136. },
  137. // 是否支持多选
  138. multiple: {
  139. type: Boolean,
  140. default: true,
  141. },
  142. // 图片尺寸
  143. size: {
  144. type: Number,
  145. default: 100,
  146. },
  147. // 占位符文本
  148. placeholder: {
  149. type: String,
  150. default: '',
  151. },
  152. // 是否显示提示信息
  153. showTip: {
  154. type: Boolean,
  155. default: true,
  156. },
  157. // 精简模式
  158. compact: {
  159. type: Boolean,
  160. default: false,
  161. },
  162. });
  163. const emit = defineEmits(['update:modelValue', 'change']);
  164. // 文件输入框引用
  165. const fileInputRef = ref();
  166. // 图片列表
  167. const imageList = ref([...props.modelValue]);
  168. // 计算接受的文件类型字符串
  169. const acceptString = computed(() => {
  170. return props.accept.map((type) => `.${type}`).join(',');
  171. });
  172. // 监听外部数据变化
  173. watch(
  174. () => props.modelValue,
  175. (newValue) => {
  176. imageList.value = [...newValue];
  177. },
  178. { deep: true },
  179. );
  180. // 监听内部数据变化
  181. watch(
  182. imageList,
  183. (newValue) => {
  184. emit('update:modelValue', newValue);
  185. emit('change', newValue);
  186. },
  187. { deep: true },
  188. );
  189. // 处理上传点击
  190. const handleUpload = () => {
  191. if (props.directUpload) {
  192. // 直传模式,直接打开文件选择
  193. fileInputRef.value?.click();
  194. } else {
  195. // 非直传模式,打开文件管理弹窗
  196. openFileManager();
  197. }
  198. };
  199. // 处理文件选择
  200. const handleFileSelect = async (event) => {
  201. const files = Array.from(event.target.files);
  202. if (!files.length) return;
  203. // 检查数量限制
  204. if (props.maxCount && imageList.value.length + files.length > props.maxCount) {
  205. ElMessage.warning(`最多只能上传${props.maxCount}张图片`);
  206. return;
  207. }
  208. // 验证文件
  209. const validFiles = [];
  210. for (const file of files) {
  211. if (validateFile(file)) {
  212. validFiles.push(file);
  213. }
  214. }
  215. if (validFiles.length === 0) return;
  216. // 上传文件
  217. try {
  218. const uploadPromises = validFiles.map((file) => uploadFile(file));
  219. const results = await Promise.all(uploadPromises);
  220. // 添加成功上传的图片
  221. results.forEach((result) => {
  222. if (result.success) {
  223. imageList.value.push(result.url);
  224. }
  225. });
  226. ElMessage.success(`成功上传${results.filter((r) => r.success).length}张图片`);
  227. } catch (error) {
  228. ElMessage.error('上传失败:' + error.message);
  229. }
  230. // 清空文件输入框
  231. event.target.value = '';
  232. };
  233. // 验证文件
  234. const validateFile = (file) => {
  235. // 检查文件类型
  236. const fileExtension = file.name.split('.').pop().toLowerCase();
  237. if (!props.accept.includes(fileExtension)) {
  238. ElMessage.warning(`不支持${fileExtension}格式,请选择${props.accept.join('、')}格式的图片`);
  239. return false;
  240. }
  241. // 检查文件大小
  242. const fileSizeMB = file.size / 1024 / 1024;
  243. if (props.maxSize && fileSizeMB > props.maxSize) {
  244. ElMessage.warning(`图片大小不能超过${props.maxSize}MB`);
  245. return false;
  246. }
  247. return true;
  248. };
  249. // 上传文件
  250. const uploadFile = async (file) => {
  251. try {
  252. const response = await adminApi.file.upload({}, file);
  253. if (response.code == '200') {
  254. return {
  255. success: true,
  256. url: response.data.url,
  257. };
  258. } else {
  259. throw new Error(response.msg || '上传失败');
  260. }
  261. } catch (error) {
  262. console.error('上传文件失败:', error);
  263. return {
  264. success: false,
  265. error: error.message,
  266. };
  267. }
  268. };
  269. // 打开文件管理器(非直传模式)
  270. const openFileManager = () => {
  271. // 这里可以集成现有的文件管理器组件
  272. console.log('打开文件管理器');
  273. ElMessage.info('文件管理器功能待实现');
  274. };
  275. // 图片预览状态
  276. const previewVisible = ref(false);
  277. const previewImageUrl = ref('');
  278. const previewImageList = ref([]);
  279. const previewInitialIndex = ref(0);
  280. // 预览图片
  281. const previewImage = (url, index = 0) => {
  282. previewImageUrl.value = url;
  283. previewImageList.value = [...imageList.value];
  284. previewInitialIndex.value = index;
  285. previewVisible.value = true;
  286. };
  287. // 关闭预览
  288. const closePreview = () => {
  289. previewVisible.value = false;
  290. previewImageUrl.value = '';
  291. previewImageList.value = [];
  292. previewInitialIndex.value = 0;
  293. };
  294. // 删除图片
  295. const removeImage = (index) => {
  296. imageList.value.splice(index, 1);
  297. };
  298. // 处理拖拽排序
  299. const handleSort = () => {
  300. // 拖拽排序后自动触发 watch 更新
  301. console.log('图片排序已更新');
  302. };
  303. </script>
  304. <style lang="scss" scoped>
  305. .sa-upload-image {
  306. .upload-container {
  307. gap: 8px;
  308. }
  309. .image-item {
  310. position: relative;
  311. border-radius: 6px;
  312. overflow: hidden;
  313. border: 1px solid #dcdfe6;
  314. .el-image {
  315. width: 100%;
  316. height: 100%;
  317. }
  318. .image-error {
  319. display: flex;
  320. align-items: center;
  321. justify-content: center;
  322. width: 100%;
  323. height: 100%;
  324. background: #f5f7fa;
  325. color: #909399;
  326. }
  327. .image-mask {
  328. position: absolute;
  329. top: 0;
  330. left: 0;
  331. right: 0;
  332. bottom: 0;
  333. background: rgba(0, 0, 0, 0.6);
  334. display: flex;
  335. align-items: center;
  336. justify-content: center;
  337. gap: 8px;
  338. opacity: 0;
  339. transition: opacity 0.3s;
  340. .el-icon {
  341. color: white;
  342. font-size: 16px;
  343. cursor: pointer;
  344. padding: 4px;
  345. border-radius: 2px;
  346. transition: background-color 0.3s;
  347. &:hover {
  348. background: rgba(255, 255, 255, 0.2);
  349. }
  350. &.sortable-drag {
  351. cursor: move;
  352. }
  353. }
  354. }
  355. &:hover .image-mask {
  356. opacity: 1;
  357. }
  358. }
  359. .upload-trigger {
  360. display: flex;
  361. flex-direction: column;
  362. align-items: center;
  363. justify-content: center;
  364. border: 2px dashed #dcdfe6;
  365. border-radius: 6px;
  366. cursor: pointer;
  367. transition: border-color 0.3s;
  368. background: #fafafa;
  369. &:hover {
  370. // 使用系统主色调
  371. border-color: var(--el-color-primary);
  372. }
  373. .upload-icon {
  374. font-size: 24px;
  375. color: #8c939d;
  376. margin-bottom: 4px;
  377. }
  378. .upload-text {
  379. font-size: 12px;
  380. color: #8c939d;
  381. }
  382. }
  383. .upload-tip {
  384. margin-top: 8px;
  385. font-size: 12px;
  386. color: #909399;
  387. line-height: 1.4;
  388. }
  389. /* 精简模式样式 */
  390. .compact-mode {
  391. border: 1px solid #dcdfe6;
  392. border-radius: 4px;
  393. &:hover {
  394. border-color: var(--el-color-primary);
  395. }
  396. }
  397. .compact-mask {
  398. background: transparent;
  399. pointer-events: none;
  400. .el-icon {
  401. position: absolute;
  402. top: 2px;
  403. right: 2px;
  404. background: rgba(0, 0, 0, 0.8);
  405. border-radius: 50%;
  406. padding: 1px;
  407. pointer-events: auto;
  408. width: 16px;
  409. height: 16px;
  410. display: flex;
  411. align-items: center;
  412. justify-content: center;
  413. font-size: 12px;
  414. }
  415. }
  416. .compact-trigger {
  417. border: 1px dashed #dcdfe6;
  418. border-radius: 4px;
  419. background: #fafafa;
  420. transition: all 0.3s;
  421. &:hover {
  422. border-color: var(--el-color-primary);
  423. background: var(--el-color-primary-light-9);
  424. }
  425. .upload-icon {
  426. color: #8c939d;
  427. }
  428. &:hover .upload-icon {
  429. color: var(--el-color-primary);
  430. }
  431. }
  432. }
  433. </style>