From 50891e99ac572897ed66090b0237885013bd8cd0 Mon Sep 17 00:00:00 2001
From: 疯狂的狮子Li <15040126243@163.com>
Date: 星期三, 09 八月 2023 12:59:18 +0800
Subject: [PATCH] fix 修复 无法获取token问题 将 globalHeaders 改为函数

---
 src/components/ImageUpload/index.vue |  277 +++++++++++++++++++++++++++----------------------------
 1 files changed, 135 insertions(+), 142 deletions(-)

diff --git a/src/components/ImageUpload/index.vue b/src/components/ImageUpload/index.vue
index 8cad89c..d8ed32b 100644
--- a/src/components/ImageUpload/index.vue
+++ b/src/components/ImageUpload/index.vue
@@ -17,7 +17,9 @@
       :on-preview="handlePictureCardPreview"
       :class="{ hide: fileList.length >= limit }"
     >
-      <el-icon class="avatar-uploader-icon"><plus /></el-icon>
+      <el-icon class="avatar-uploader-icon">
+        <plus />
+      </el-icon>
     </el-upload>
     <!-- 涓婁紶鎻愮ず -->
     <div class="el-upload__tip" v-if="showTip">
@@ -31,187 +33,178 @@
       鐨勬枃浠�
     </div>
 
-    <el-dialog
-      v-model="dialogVisible"
-      title="棰勮"
-      width="800px"
-      append-to-body
-    >
-      <img
-        :src="dialogImageUrl"
-        style="display: block; max-width: 100%; margin: 0 auto"
-      />
+    <el-dialog v-model="dialogVisible" title="棰勮" width="800px" append-to-body>
+      <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
     </el-dialog>
   </div>
 </template>
 
-<script setup>
-import { getToken } from "@/utils/auth";
+<script setup lang="ts">
 import { listByIds, delOss } from "@/api/system/oss";
+import { ComponentInternalInstance } from "vue";
+import { OssVO } from "@/api/system/oss/types";
+import { propTypes } from '@/utils/propTypes';
+import {globalHeaders} from "@/utils/request";
 
 const props = defineProps({
-  modelValue: [String, Object, Array],
-  // 鍥剧墖鏁伴噺闄愬埗
-  limit: {
-    type: Number,
-    default: 5,
-  },
-  // 澶у皬闄愬埗(MB)
-  fileSize: {
-    type: Number,
-    default: 5,
-  },
-  // 鏂囦欢绫诲瀷, 渚嬪['png', 'jpg', 'jpeg']
-  fileType: {
-    type: Array,
-    default: () => ["png", "jpg", "jpeg"],
-  },
-  // 鏄惁鏄剧ず鎻愮ず
-  isShowTip: {
-    type: Boolean,
-    default: true
-  },
+    modelValue: [String, Object, Array],
+    // 鍥剧墖鏁伴噺闄愬埗
+    limit: propTypes.number.def(5),
+    // 澶у皬闄愬埗(MB)
+    fileSize: propTypes.number.def(5),
+    // 鏂囦欢绫诲瀷, 渚嬪['png', 'jpg', 'jpeg']
+    fileType: propTypes.array.def(["png", "jpg", "jpeg"]),
+    // 鏄惁鏄剧ず鎻愮ず
+    isShowTip: {
+        type: Boolean,
+        default: true
+    },
 });
 
-const { proxy } = getCurrentInstance();
-const emit = defineEmits();
+const { proxy } = getCurrentInstance() as ComponentInternalInstance;
+const emit = defineEmits(['update:modelValue']);
 const number = ref(0);
-const uploadList = ref([]);
+const uploadList = ref<any[]>([]);
 const dialogImageUrl = ref("");
 const dialogVisible = ref(false);
+
 const baseUrl = import.meta.env.VITE_APP_BASE_API;
-const uploadImgUrl = ref(baseUrl + "/system/oss/upload"); // 涓婁紶鐨勫浘鐗囨湇鍔″櫒鍦板潃
-const headers = ref({ Authorization: "Bearer " + getToken() });
-const fileList = ref([]);
+const uploadImgUrl = ref(baseUrl + "/resource/oss/upload"); // 涓婁紶鐨勫浘鐗囨湇鍔″櫒鍦板潃
+const headers = ref(globalHeaders());
+
+const fileList = ref<any[]>([]);
 const showTip = computed(
-  () => props.isShowTip && (props.fileType || props.fileSize)
+    () => props.isShowTip && (props.fileType || props.fileSize)
 );
 
-watch(() => props.modelValue, async val => {
-  if (val) {
-    // 棣栧厛灏嗗�艰浆涓烘暟缁�
-    let list;
-    if (Array.isArray(val)) {
-      list = val;
-    } else {
-      await listByIds(val).then(res => {
-        list = res.data;
-      })
-    }
-    // 鐒跺悗灏嗘暟缁勮浆涓哄璞℃暟缁�
-    fileList.value = list.map(item => {
-      // 瀛楃涓插洖鏄惧鐞� 濡傛灉姝ゅ瀛樼殑鏄痷rl鍙洿鎺ュ洖鏄� 濡傛灉瀛樼殑鏄痠d闇�瑕佽皟鐢ㄦ帴鍙f煡鍑烘潵
-      if (typeof item === "string") {
-        item = { name: item, url: item };
-      } else {
-        // 姝ゅname浣跨敤ossId 闃叉鍒犻櫎鍑虹幇閲嶅悕
-        item = { name: item.ossId, url: item.url, ossId: item.ossId };
-      }
-      return item;
-    });
-  } else {
-    fileList.value = [];
-    return [];
-  }
-},{ deep: true, immediate: true });
+const imageUploadRef = ref<ElUploadInstance>();
 
-// 涓婁紶鍓峫oading鍔犺浇
-function handleBeforeUpload(file) {
-  let isImg = false;
-  if (props.fileType.length) {
-    let fileExtension = "";
-    if (file.name.lastIndexOf(".") > -1) {
-      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
+watch(() => props.modelValue, async val => {
+    if (val) {
+        // 棣栧厛灏嗗�艰浆涓烘暟缁�
+        let list: OssVO[] = [];
+        if (Array.isArray(val)) {
+            list = val as OssVO[];
+        } else {
+            const res = await listByIds(val as string)
+            list = res.data
+        }
+        // 鐒跺悗灏嗘暟缁勮浆涓哄璞℃暟缁�
+        fileList.value = list.map(item => {
+            // 瀛楃涓插洖鏄惧鐞� 濡傛灉姝ゅ瀛樼殑鏄痷rl鍙洿鎺ュ洖鏄� 濡傛灉瀛樼殑鏄痠d闇�瑕佽皟鐢ㄦ帴鍙f煡鍑烘潵
+            let itemData;
+            if (typeof item === "string") {
+                itemData = { name: item, url: item };
+            } else {
+                // 姝ゅname浣跨敤ossId 闃叉鍒犻櫎鍑虹幇閲嶅悕
+                itemData = { name: item.ossId, url: item.url, ossId: item.ossId };
+            }
+            return itemData;
+        });
+    } else {
+        fileList.value = [];
+        return [];
     }
-    isImg = props.fileType.some((type) => {
-      if (file.type.indexOf(type) > -1) return true;
-      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
-      return false;
-    });
-  } else {
-    isImg = file.type.indexOf("image") > -1;
-  }
-  if (!isImg) {
-    proxy.$modal.msgError(
-      `鏂囦欢鏍煎紡涓嶆纭�, 璇蜂笂浼�${props.fileType.join("/")}鍥剧墖鏍煎紡鏂囦欢!`
-    );
-    return false;
-  }
-  if (props.fileSize) {
-    const isLt = file.size / 1024 / 1024 < props.fileSize;
-    if (!isLt) {
-      proxy.$modal.msgError(`涓婁紶澶村儚鍥剧墖澶у皬涓嶈兘瓒呰繃 ${props.fileSize} MB!`);
-      return false;
+}, { deep: true, immediate: true });
+
+/** 涓婁紶鍓峫oading鍔犺浇 */
+const handleBeforeUpload = (file: any) => {
+    let isImg = false;
+    if (props.fileType.length) {
+        let fileExtension = "";
+        if (file.name.lastIndexOf(".") > -1) {
+            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
+        }
+        isImg = props.fileType.some((type: any) => {
+            if (file.type.indexOf(type) > -1) return true;
+            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
+            return false;
+        });
+    } else {
+        isImg = file.type.indexOf("image") > -1;
     }
-  }
-  proxy.$modal.loading("姝e湪涓婁紶鍥剧墖锛岃绋嶅��...");
-  number.value++;
+    if (!isImg) {
+        proxy?.$modal.msgError(
+            `鏂囦欢鏍煎紡涓嶆纭�, 璇蜂笂浼�${props.fileType.join("/")}鍥剧墖鏍煎紡鏂囦欢!`
+        );
+        return false;
+    }
+    if (props.fileSize) {
+        const isLt = file.size / 1024 / 1024 < props.fileSize;
+        if (!isLt) {
+            proxy?.$modal.msgError(`涓婁紶澶村儚鍥剧墖澶у皬涓嶈兘瓒呰繃 ${props.fileSize} MB!`);
+            return false;
+        }
+    }
+    proxy?.$modal.loading("姝e湪涓婁紶鍥剧墖锛岃绋嶅��...");
+    number.value++;
 }
 
 // 鏂囦欢涓暟瓒呭嚭
-function handleExceed() {
-  proxy.$modal.msgError(`涓婁紶鏂囦欢鏁伴噺涓嶈兘瓒呰繃 ${props.limit} 涓�!`);
+const handleExceed = () => {
+    proxy?.$modal.msgError(`涓婁紶鏂囦欢鏁伴噺涓嶈兘瓒呰繃 ${props.limit} 涓�!`);
 }
 
 // 涓婁紶鎴愬姛鍥炶皟
-function handleUploadSuccess(res, file) {
-  if (res.code === 200) {
-    uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
-    uploadedSuccessfully();
-  } else {
-    number.value--;
-    proxy.$modal.closeLoading();
-    proxy.$modal.msgError(res.msg);
-    proxy.$refs.imageUpload.handleRemove(file);
-    uploadedSuccessfully();
-  }
+const handleUploadSuccess = (res: any, file: UploadFile) => {
+    if (res.code === 200) {
+        uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
+        uploadedSuccessfully();
+    } else {
+        number.value--;
+        proxy?.$modal.closeLoading();
+        proxy?.$modal.msgError(res.msg);
+        imageUploadRef.value?.handleRemove(file);
+        uploadedSuccessfully();
+    }
 }
 
 // 鍒犻櫎鍥剧墖
-function handleDelete(file) {
-  const findex = fileList.value.map(f => f.name).indexOf(file.name);
-  if (findex > -1 && uploadList.value.length === number.value) {
-    let ossId = fileList.value[findex].ossId;
-    delOss(ossId);
-    fileList.value.splice(findex, 1);
-    emit("update:modelValue", listToString(fileList.value));
-    return false;
-  }
+const handleDelete = (file: UploadFile): boolean => {
+    const findex = fileList.value.map(f => f.name).indexOf(file.name);
+    if (findex > -1 && uploadList.value.length === number.value) {
+        let ossId = fileList.value[findex].ossId;
+        delOss(ossId);
+        fileList.value.splice(findex, 1);
+        emit("update:modelValue", listToString(fileList.value));
+        return false;
+    }
+    return true;
 }
 
 // 涓婁紶缁撴潫澶勭悊
-function uploadedSuccessfully() {
-  if (number.value > 0 && uploadList.value.length === number.value) {
-    fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
-    uploadList.value = [];
-    number.value = 0;
-    emit("update:modelValue", listToString(fileList.value));
-    proxy.$modal.closeLoading();
-  }
+const uploadedSuccessfully = () => {
+    if (number.value > 0 && uploadList.value.length === number.value) {
+        fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
+        uploadList.value = [];
+        number.value = 0;
+        emit("update:modelValue", listToString(fileList.value));
+        proxy?.$modal.closeLoading();
+    }
 }
 
 // 涓婁紶澶辫触
-function handleUploadError(res) {
-  proxy.$modal.msgError("涓婁紶鍥剧墖澶辫触");
-  proxy.$modal.closeLoading();
+const handleUploadError = () => {
+    proxy?.$modal.msgError("涓婁紶鍥剧墖澶辫触");
+    proxy?.$modal.closeLoading();
 }
 
 // 棰勮
-function handlePictureCardPreview(file) {
-  dialogImageUrl.value = file.url;
-  dialogVisible.value = true;
+const handlePictureCardPreview = (file: any) => {
+    dialogImageUrl.value = file.url;
+    dialogVisible.value = true;
 }
 
 // 瀵硅薄杞垚鎸囧畾瀛楃涓插垎闅�
-function listToString(list, separator) {
-  let strs = "";
-  separator = separator || ",";
-  for (let i in list) {
-    if(undefined !== list[i].ossId && list[i].url.indexOf("blob:") !== 0) {
-      strs += list[i].ossId + separator;
+const listToString = (list: any[], separator?: string) => {
+    let strs = "";
+    separator = separator || ",";
+    for (let i in list) {
+        if (undefined !== list[i].ossId && list[i].url.indexOf("blob:") !== 0) {
+            strs += list[i].ossId + separator;
+        }
     }
-  }
-  return strs != "" ? strs.substr(0, strs.length - 1) : "";
+    return strs != "" ? strs.substring(0, strs.length - 1) : "";
 }
 </script>
 
@@ -220,4 +213,4 @@
 :deep(.hide .el-upload--picture-card) {
     display: none;
 }
-</style>
\ No newline at end of file
+</style>

--
Gitblit v1.9.3