index.vue 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. <template>
  2. <div class="component-upload-image">
  3. <el-upload
  4. ref="imageUploadRef"
  5. multiple
  6. :action="uploadImgUrl"
  7. list-type="picture-card"
  8. :on-success="handleUploadSuccess"
  9. :before-upload="handleBeforeUpload"
  10. :limit="limit"
  11. :accept="fileAccept"
  12. :on-error="handleUploadError"
  13. :on-exceed="handleExceed"
  14. :before-remove="handleDelete"
  15. :show-file-list="true"
  16. :headers="headers"
  17. :file-list="fileList"
  18. :on-preview="handlePictureCardPreview"
  19. :class="{ hide: fileList.length >= limit }"
  20. >
  21. <el-icon class="avatar-uploader-icon">
  22. <plus />
  23. </el-icon>
  24. </el-upload>
  25. <!-- 上传提示 -->
  26. <div v-if="showTip" class="el-upload__tip">
  27. 请上传
  28. <template v-if="fileSize">
  29. 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
  30. </template>
  31. <template v-if="fileType">
  32. 格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
  33. </template>
  34. 的文件
  35. </div>
  36. <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
  37. <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
  38. </el-dialog>
  39. </div>
  40. </template>
  41. <script setup lang="ts">
  42. import { listByIds, delOss } from '@/api/system/oss';
  43. import { OssVO } from '@/api/system/oss/types';
  44. import { propTypes } from '@/utils/propTypes';
  45. import { globalHeaders } from '@/utils/request';
  46. import { compressAccurately } from 'image-conversion';
  47. const props = defineProps({
  48. modelValue: {
  49. type: [String, Object, Array],
  50. default: () => []
  51. },
  52. // 图片数量限制
  53. limit: propTypes.number.def(15),
  54. // 大小限制(MB)
  55. fileSize: propTypes.number.def(10),
  56. // 文件类型, 例如['png', 'jpg', 'jpeg']
  57. fileType: propTypes.array.def(['png', 'jpg', 'jpeg']),
  58. // 是否显示提示
  59. isShowTip: {
  60. type: Boolean,
  61. default: true
  62. },
  63. // 是否支持压缩,默认否
  64. compressSupport: {
  65. type: Boolean,
  66. default: false
  67. },
  68. // 压缩目标大小,单位KB。默认300KB以上文件才压缩,并压缩至300KB以内
  69. compressTargetSize: propTypes.number.def(300)
  70. });
  71. const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  72. const emit = defineEmits(['update:modelValue']);
  73. const number = ref(0);
  74. const uploadList = ref<any[]>([]);
  75. const dialogImageUrl = ref('');
  76. const dialogVisible = ref(false);
  77. const baseUrl = import.meta.env.VITE_APP_BASE_API;
  78. const uploadImgUrl = ref(baseUrl + '/resource/oss/upload'); // 上传的图片服务器地址
  79. const headers = ref(globalHeaders());
  80. const fileList = ref<any[]>([]);
  81. const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));
  82. const imageUploadRef = ref<ElUploadInstance>();
  83. // 监听 fileType 变化,更新 fileAccept
  84. const fileAccept = computed(() => props.fileType.map((type) => `.${type}`).join(','));
  85. watch(
  86. () => props.modelValue,
  87. async (val: string) => {
  88. if (val) {
  89. // 首先将值转为数组
  90. let list: OssVO[] = [];
  91. if (Array.isArray(val)) {
  92. list = val as OssVO[];
  93. } else if (typeof val === 'string') {
  94. // 检查是否包含逗号分隔的URL
  95. if (val.includes(',')) {
  96. // 多个URL用逗号分隔
  97. const urls = val.split(',').filter((url) => url.trim());
  98. list = urls.map((url, index) => ({
  99. ossId: url,
  100. url: url.trim(),
  101. originalName: `image_${index + 1}`
  102. })) as any;
  103. } else if (val.startsWith('http://') || val.startsWith('https://')) {
  104. // 单个URL
  105. list = [{ ossId: val, url: val, originalName: 'image' }] as any;
  106. } else {
  107. // 如果是OSS ID,调用接口获取详细信息
  108. try {
  109. const res = await listByIds(val);
  110. list = res.data;
  111. } catch (error) {
  112. console.error('调用listByIds接口失败:', error);
  113. list = [];
  114. }
  115. }
  116. }
  117. // 然后将数组转为对象数组
  118. fileList.value = list.map((item, index) => {
  119. // 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
  120. let itemData;
  121. if (typeof item === 'string') {
  122. itemData = { name: item, url: item };
  123. } else {
  124. // 此处name使用url 防止删除出现重名,对于URL格式使用url_index的格式
  125. const name = item.url && (item.url.startsWith('http://') || item.url.startsWith('https://')) ? `${item.url}_${index}` : item.ossId;
  126. itemData = { name: name, url: item.url, ossId: item.ossId };
  127. }
  128. return itemData;
  129. });
  130. } else {
  131. fileList.value = [];
  132. return [];
  133. }
  134. },
  135. { deep: true, immediate: true }
  136. );
  137. /** 上传前loading加载 */
  138. const handleBeforeUpload = (file: any) => {
  139. let isImg = false;
  140. if (props.fileType.length) {
  141. let fileExtension = '';
  142. if (file.name.lastIndexOf('.') > -1) {
  143. fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
  144. }
  145. isImg = props.fileType.some((type: any) => {
  146. if (file.type.indexOf(type) > -1) return true;
  147. if (fileExtension && fileExtension.indexOf(type) > -1) return true;
  148. return false;
  149. });
  150. } else {
  151. isImg = file.type.indexOf('image') > -1;
  152. }
  153. if (!isImg) {
  154. proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}图片格式文件!`);
  155. return false;
  156. }
  157. if (file.name.includes(',')) {
  158. proxy?.$modal.msgError('文件名不正确,不能包含英文逗号!');
  159. return false;
  160. }
  161. if (props.fileSize) {
  162. const isLt = file.size / 1024 / 1024 < props.fileSize;
  163. if (!isLt) {
  164. proxy?.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
  165. return false;
  166. }
  167. }
  168. //压缩图片,开启压缩并且大于指定的压缩大小时才压缩
  169. if (props.compressSupport && file.size / 1024 > props.compressTargetSize) {
  170. proxy?.$modal.loading('正在上传图片,请稍候...');
  171. number.value++;
  172. return compressAccurately(file, props.compressTargetSize);
  173. } else {
  174. proxy?.$modal.loading('正在上传图片,请稍候...');
  175. number.value++;
  176. }
  177. };
  178. // 文件个数超出
  179. const handleExceed = () => {
  180. proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  181. };
  182. // 上传成功回调
  183. const handleUploadSuccess = (res: any, file: UploadFile) => {
  184. if (res.code === 200) {
  185. uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
  186. uploadedSuccessfully();
  187. } else {
  188. number.value--;
  189. proxy?.$modal.closeLoading();
  190. proxy?.$modal.msgError(res.msg);
  191. imageUploadRef.value?.handleRemove(file);
  192. uploadedSuccessfully();
  193. }
  194. };
  195. // 删除图片
  196. const handleDelete = (file: UploadFile): boolean => {
  197. const findex = fileList.value.map((f) => f.name).indexOf(file.name);
  198. if (findex > -1 && uploadList.value.length === number.value) {
  199. const ossId = fileList.value[findex].ossId;
  200. delOss(ossId);
  201. fileList.value.splice(findex, 1);
  202. emit('update:modelValue', listToString(fileList.value));
  203. return false;
  204. }
  205. return true;
  206. };
  207. // 上传结束处理
  208. const uploadedSuccessfully = () => {
  209. if (number.value > 0 && uploadList.value.length === number.value) {
  210. fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
  211. uploadList.value = [];
  212. number.value = 0;
  213. emit('update:modelValue', listToString(fileList.value));
  214. proxy?.$modal.closeLoading();
  215. }
  216. };
  217. // 上传失败
  218. const handleUploadError = () => {
  219. proxy?.$modal.msgError('上传图片失败');
  220. proxy?.$modal.closeLoading();
  221. };
  222. // 预览
  223. const handlePictureCardPreview = (file: any) => {
  224. dialogImageUrl.value = file.url;
  225. dialogVisible.value = true;
  226. };
  227. // 对象转成指定字符串分隔
  228. const listToString = (list: any[], separator?: string) => {
  229. let strs = '';
  230. separator = separator || ',';
  231. for (const i in list) {
  232. if (undefined !== list[i].url && list[i].url.indexOf('blob:') !== 0) {
  233. // 始终返回URL而不是ossId
  234. strs += list[i].url + separator;
  235. }
  236. }
  237. return strs != '' ? strs.substring(0, strs.length - 1) : '';
  238. };
  239. </script>
  240. <style lang="scss" scoped>
  241. // .el-upload--picture-card 控制加号部分
  242. :deep(.hide .el-upload--picture-card) {
  243. display: none;
  244. }
  245. </style>