index.vue 6.7 KB

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