index.vue 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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(5),
  54. // 大小限制(MB)
  55. fileSize: propTypes.number.def(5),
  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' && (val.startsWith('http://') || val.startsWith('https://'))) {
  94. // 值已经是URL(后端直接返回了URL),跳过listByIds,直接按逗号分隔构造回显数据
  95. const urls = val.split(',').filter((u) => u.trim());
  96. fileList.value = urls.map((url, index) => ({
  97. name: url,
  98. url: url,
  99. ossId: url
  100. }));
  101. return;
  102. } else {
  103. const res = await listByIds(val);
  104. list = res.data;
  105. }
  106. // 然后将数组转为对象数组
  107. fileList.value = list.map((item) => {
  108. // 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
  109. let itemData;
  110. if (typeof item === 'string') {
  111. // URL字符串也设置ossId,与上方URL绕过分支保持一致,确保listToString能正确追踪
  112. itemData = { name: item, url: item, ossId: item };
  113. } else {
  114. // 此处name使用ossId 防止删除出现重名
  115. itemData = { name: item.ossId, url: item.url, ossId: item.ossId };
  116. }
  117. return itemData;
  118. });
  119. } else {
  120. fileList.value = [];
  121. return [];
  122. }
  123. },
  124. { deep: true, immediate: true }
  125. );
  126. /** 上传前loading加载 */
  127. const handleBeforeUpload = (file: any) => {
  128. let isImg = false;
  129. if (props.fileType.length) {
  130. let fileExtension = '';
  131. if (file.name.lastIndexOf('.') > -1) {
  132. fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
  133. }
  134. isImg = props.fileType.some((type: any) => {
  135. if (file.type.indexOf(type) > -1) return true;
  136. if (fileExtension && fileExtension.indexOf(type) > -1) return true;
  137. return false;
  138. });
  139. } else {
  140. isImg = file.type.indexOf('image') > -1;
  141. }
  142. if (!isImg) {
  143. proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}图片格式文件!`);
  144. return false;
  145. }
  146. if (file.name.includes(',')) {
  147. proxy?.$modal.msgError('文件名不正确,不能包含英文逗号!');
  148. return false;
  149. }
  150. if (props.fileSize) {
  151. const isLt = file.size / 1024 / 1024 < props.fileSize;
  152. if (!isLt) {
  153. proxy?.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
  154. return false;
  155. }
  156. }
  157. //压缩图片,开启压缩并且大于指定的压缩大小时才压缩
  158. if (props.compressSupport && file.size / 1024 > props.compressTargetSize) {
  159. proxy?.$modal.loading('正在上传图片,请稍候...');
  160. number.value++;
  161. return compressAccurately(file, props.compressTargetSize);
  162. } else {
  163. proxy?.$modal.loading('正在上传图片,请稍候...');
  164. number.value++;
  165. }
  166. };
  167. // 文件个数超出
  168. const handleExceed = () => {
  169. proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  170. };
  171. // 上传成功回调
  172. const handleUploadSuccess = (res: any, file: UploadFile) => {
  173. if (res.code === 200) {
  174. uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
  175. uploadedSuccessfully();
  176. } else {
  177. number.value--;
  178. proxy?.$modal.closeLoading();
  179. proxy?.$modal.msgError(res.msg);
  180. imageUploadRef.value?.handleRemove(file);
  181. uploadedSuccessfully();
  182. }
  183. };
  184. // 删除图片
  185. const handleDelete = (file: UploadFile): boolean => {
  186. const findex = fileList.value.map((f) => f.name).indexOf(file.name);
  187. if (findex > -1 && uploadList.value.length === number.value) {
  188. const ossId = fileList.value[findex].ossId;
  189. delOss(ossId);
  190. fileList.value.splice(findex, 1);
  191. emit('update:modelValue', listToString(fileList.value));
  192. return false;
  193. }
  194. return true;
  195. };
  196. // 上传结束处理
  197. const uploadedSuccessfully = () => {
  198. if (number.value > 0 && uploadList.value.length === number.value) {
  199. fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
  200. uploadList.value = [];
  201. number.value = 0;
  202. emit('update:modelValue', listToString(fileList.value));
  203. proxy?.$modal.closeLoading();
  204. }
  205. };
  206. // 上传失败
  207. const handleUploadError = () => {
  208. proxy?.$modal.msgError('上传图片失败');
  209. proxy?.$modal.closeLoading();
  210. };
  211. // 预览
  212. const handlePictureCardPreview = (file: any) => {
  213. dialogImageUrl.value = file.url;
  214. dialogVisible.value = true;
  215. };
  216. // 对象转成指定字符串分隔
  217. const listToString = (list: any[], separator?: string) => {
  218. let strs = '';
  219. separator = separator || ',';
  220. for (const i in list) {
  221. if (undefined !== list[i].ossId && list[i].url.indexOf('blob:') !== 0) {
  222. strs += list[i].url + separator;
  223. }
  224. }
  225. return strs != '' ? strs.substring(0, strs.length - 1) : '';
  226. };
  227. </script>
  228. <style lang="scss" scoped>
  229. // .el-upload--picture-card 控制加号部分
  230. :deep(.hide .el-upload--picture-card) {
  231. display: none;
  232. }
  233. </style>