index.vue 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 (file.name.includes(',')) {
  134. proxy?.$modal.msgError('文件名不正确,不能包含英文逗号!');
  135. return false;
  136. }
  137. if (props.fileSize) {
  138. const isLt = file.size / 1024 / 1024 < props.fileSize;
  139. if (!isLt) {
  140. proxy?.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
  141. return false;
  142. }
  143. }
  144. //压缩图片,开启压缩并且大于指定的压缩大小时才压缩
  145. if (props.compressSupport && file.size / 1024 > props.compressTargetSize) {
  146. proxy?.$modal.loading('正在上传图片,请稍候...');
  147. number.value++;
  148. return compressAccurately(file, props.compressTargetSize);
  149. } else {
  150. proxy?.$modal.loading('正在上传图片,请稍候...');
  151. number.value++;
  152. }
  153. };
  154. // 文件个数超出
  155. const handleExceed = () => {
  156. proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  157. };
  158. // 上传成功回调
  159. const handleUploadSuccess = (res: any, file: UploadFile) => {
  160. if (res.code === 200) {
  161. uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
  162. uploadedSuccessfully();
  163. } else {
  164. number.value--;
  165. proxy?.$modal.closeLoading();
  166. proxy?.$modal.msgError(res.msg);
  167. imageUploadRef.value?.handleRemove(file);
  168. uploadedSuccessfully();
  169. }
  170. };
  171. // 删除图片
  172. const handleDelete = (file: UploadFile): boolean => {
  173. const findex = fileList.value.map((f) => f.name).indexOf(file.name);
  174. if (findex > -1 && uploadList.value.length === number.value) {
  175. let ossId = fileList.value[findex].ossId;
  176. delOss(ossId);
  177. fileList.value.splice(findex, 1);
  178. emit('update:modelValue', listToString(fileList.value));
  179. return false;
  180. }
  181. return true;
  182. };
  183. // 上传结束处理
  184. const uploadedSuccessfully = () => {
  185. if (number.value > 0 && uploadList.value.length === number.value) {
  186. fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
  187. uploadList.value = [];
  188. number.value = 0;
  189. emit('update:modelValue', listToString(fileList.value));
  190. proxy?.$modal.closeLoading();
  191. }
  192. };
  193. // 上传失败
  194. const handleUploadError = () => {
  195. proxy?.$modal.msgError('上传图片失败');
  196. proxy?.$modal.closeLoading();
  197. };
  198. // 预览
  199. const handlePictureCardPreview = (file: any) => {
  200. dialogImageUrl.value = file.url;
  201. dialogVisible.value = true;
  202. };
  203. // 对象转成指定字符串分隔
  204. const listToString = (list: any[], separator?: string) => {
  205. let strs = '';
  206. separator = separator || ',';
  207. for (let i in list) {
  208. if (undefined !== list[i].ossId && list[i].url.indexOf('blob:') !== 0) {
  209. strs += list[i].ossId + separator;
  210. }
  211. }
  212. return strs != '' ? strs.substring(0, strs.length - 1) : '';
  213. };
  214. </script>
  215. <style scoped lang="scss">
  216. // .el-upload--picture-card 控制加号部分
  217. :deep(.hide .el-upload--picture-card) {
  218. display: none;
  219. }
  220. </style>