index.vue 6.8 KB

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