index.vue 7.4 KB

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