index.vue 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. const props = defineProps({
  46. modelValue: {
  47. type: [String, Object, Array],
  48. default: () => []
  49. },
  50. // 图片数量限制
  51. limit: propTypes.number.def(5),
  52. // 大小限制(MB)
  53. fileSize: propTypes.number.def(5),
  54. // 文件类型, 例如['png', 'jpg', 'jpeg']
  55. fileType: propTypes.array.def(['png', 'jpg', 'jpeg']),
  56. // 是否显示提示
  57. isShowTip: {
  58. type: Boolean,
  59. default: true
  60. }
  61. });
  62. const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  63. const emit = defineEmits(['update:modelValue']);
  64. const number = ref(0);
  65. const uploadList = ref<any[]>([]);
  66. const dialogImageUrl = ref('');
  67. const dialogVisible = ref(false);
  68. const baseUrl = import.meta.env.VITE_APP_BASE_API;
  69. const uploadImgUrl = ref(baseUrl + '/resource/oss/upload'); // 上传的图片服务器地址
  70. const headers = ref(globalHeaders());
  71. const fileList = ref<any[]>([]);
  72. const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));
  73. const imageUploadRef = ref<ElUploadInstance>();
  74. watch(
  75. () => props.modelValue,
  76. async (val: string) => {
  77. if (val) {
  78. // 首先将值转为数组
  79. let list: OssVO[] = [];
  80. if (Array.isArray(val)) {
  81. list = val as OssVO[];
  82. } else {
  83. const res = await listByIds(val);
  84. list = res.data;
  85. }
  86. // 然后将数组转为对象数组
  87. fileList.value = list.map((item) => {
  88. // 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
  89. let itemData;
  90. if (typeof item === 'string') {
  91. itemData = { name: item, url: item };
  92. } else {
  93. // 此处name使用ossId 防止删除出现重名
  94. itemData = { name: item.ossId, url: item.url, ossId: item.ossId };
  95. }
  96. return itemData;
  97. });
  98. } else {
  99. fileList.value = [];
  100. return [];
  101. }
  102. },
  103. { deep: true, immediate: true }
  104. );
  105. /** 上传前loading加载 */
  106. const handleBeforeUpload = (file: any) => {
  107. let isImg = false;
  108. if (props.fileType.length) {
  109. let fileExtension = '';
  110. if (file.name.lastIndexOf('.') > -1) {
  111. fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
  112. }
  113. isImg = props.fileType.some((type: any) => {
  114. if (file.type.indexOf(type) > -1) return true;
  115. if (fileExtension && fileExtension.indexOf(type) > -1) return true;
  116. return false;
  117. });
  118. } else {
  119. isImg = file.type.indexOf('image') > -1;
  120. }
  121. if (!isImg) {
  122. proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}图片格式文件!`);
  123. return false;
  124. }
  125. if (props.fileSize) {
  126. const isLt = file.size / 1024 / 1024 < props.fileSize;
  127. if (!isLt) {
  128. proxy?.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
  129. return false;
  130. }
  131. }
  132. proxy?.$modal.loading('正在上传图片,请稍候...');
  133. number.value++;
  134. };
  135. // 文件个数超出
  136. const handleExceed = () => {
  137. proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  138. };
  139. // 上传成功回调
  140. const handleUploadSuccess = (res: any, file: UploadFile) => {
  141. if (res.code === 200) {
  142. uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
  143. uploadedSuccessfully();
  144. } else {
  145. number.value--;
  146. proxy?.$modal.closeLoading();
  147. proxy?.$modal.msgError(res.msg);
  148. imageUploadRef.value?.handleRemove(file);
  149. uploadedSuccessfully();
  150. }
  151. };
  152. // 删除图片
  153. const handleDelete = (file: UploadFile): boolean => {
  154. const findex = fileList.value.map((f) => f.name).indexOf(file.name);
  155. if (findex > -1 && uploadList.value.length === number.value) {
  156. let ossId = fileList.value[findex].ossId;
  157. delOss(ossId);
  158. fileList.value.splice(findex, 1);
  159. emit('update:modelValue', listToString(fileList.value));
  160. return false;
  161. }
  162. return true;
  163. };
  164. // 上传结束处理
  165. const uploadedSuccessfully = () => {
  166. if (number.value > 0 && uploadList.value.length === number.value) {
  167. fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
  168. uploadList.value = [];
  169. number.value = 0;
  170. emit('update:modelValue', listToString(fileList.value));
  171. proxy?.$modal.closeLoading();
  172. }
  173. };
  174. // 上传失败
  175. const handleUploadError = () => {
  176. proxy?.$modal.msgError('上传图片失败');
  177. proxy?.$modal.closeLoading();
  178. };
  179. // 预览
  180. const handlePictureCardPreview = (file: any) => {
  181. dialogImageUrl.value = file.url;
  182. dialogVisible.value = true;
  183. };
  184. // 对象转成指定字符串分隔
  185. const listToString = (list: any[], separator?: string) => {
  186. let strs = '';
  187. separator = separator || ',';
  188. for (let i in list) {
  189. if (undefined !== list[i].ossId && list[i].url.indexOf('blob:') !== 0) {
  190. strs += list[i].ossId + separator;
  191. }
  192. }
  193. return strs != '' ? strs.substring(0, strs.length - 1) : '';
  194. };
  195. </script>
  196. <style scoped lang="scss">
  197. // .el-upload--picture-card 控制加号部分
  198. :deep(.hide .el-upload--picture-card) {
  199. display: none;
  200. }
  201. </style>