index.vue 7.2 KB

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