index.vue 6.9 KB

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