From 61161cdd698fd690860943275d296ade38e6dcf1 Mon Sep 17 00:00:00 2001
From: RuoYi <yzz_ivy@163.com>
Date: 星期四, 30 十二月 2021 10:25:40 +0800
Subject: [PATCH] 新增图片上传组件

---
 src/components/ImageUpload/index.vue |  197 +++++++++++++++++++++++++++++++++++++++++++++++++
 src/main.js                          |    3 
 2 files changed, 200 insertions(+), 0 deletions(-)

diff --git a/src/components/ImageUpload/index.vue b/src/components/ImageUpload/index.vue
new file mode 100644
index 0000000..f30eeab
--- /dev/null
+++ b/src/components/ImageUpload/index.vue
@@ -0,0 +1,197 @@
+<template>
+  <div class="component-upload-image">
+    <el-upload
+      :action="uploadImgUrl"
+      list-type="picture-card"
+      :on-success="handleUploadSuccess"
+      :before-upload="handleBeforeUpload"
+      :limit="limit"
+      :on-error="handleUploadError"
+      :on-exceed="handleExceed"
+      name="file"
+      :on-remove="handleRemove"
+      :show-file-list="true"
+      :headers="headers"
+      :file-list="fileList"
+      :on-preview="handlePictureCardPreview"
+      :class="{ hide: fileList.length >= limit }"
+    >
+      <el-icon class="avatar-uploader-icon"><plus /></el-icon>
+    </el-upload>
+    <!-- 涓婁紶鎻愮ず -->
+    <div class="el-upload__tip" v-if="showTip">
+      璇蜂笂浼�
+      <template v-if="fileSize">
+        澶у皬涓嶈秴杩� <b style="color: #f56c6c">{{ fileSize }}MB</b>
+      </template>
+      <template v-if="fileType">
+        鏍煎紡涓� <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
+      </template>
+      鐨勬枃浠�
+    </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>
+  </div>
+</template>
+
+<script setup>
+import { getToken } from "@/utils/auth";
+
+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
+  },
+});
+
+const { proxy } = getCurrentInstance();
+const emit = defineEmits();
+const dialogImageUrl = ref("");
+const dialogVisible = ref(false);
+const baseUrl = import.meta.env.VITE_APP_BASE_API;
+const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 涓婁紶鐨勫浘鐗囨湇鍔″櫒鍦板潃
+const headers = ref({ Authorization: "Bearer " + getToken() });
+const fileList = ref([]);
+const showTip = computed(
+  () => props.isShowTip && (props.fileType || props.fileSize)
+);
+
+watch(() => props.modelValue, val => {
+  if (val) {
+    // 棣栧厛灏嗗�艰浆涓烘暟缁�
+    const list = Array.isArray(val) ? val : props.modelValue.split(",");
+    // 鐒跺悗灏嗘暟缁勮浆涓哄璞℃暟缁�
+    fileList.value = list.map(item => {
+      if (typeof item === "string") {
+        if (item.indexOf(baseUrl) === -1) {
+          item = { name: baseUrl + item, url: baseUrl + item };
+        } else {
+          item = { name: item, url: item };
+        }
+      }
+      return item;
+    });
+  } else {
+    fileList.value = [];
+    return [];
+  }
+});
+
+// 鍒犻櫎鍥剧墖
+function handleRemove(file, files) {
+  const findex = fileList.value.map(f => f.name).indexOf(file.name);
+  if (findex > -1) {
+    fileList.value.splice(findex, 1);
+    emit("update:modelValue", listToString(fileList.value));
+  }
+}
+
+// 涓婁紶鎴愬姛鍥炶皟
+function handleUploadSuccess(res) {
+  fileList.value.push({ name: res.fileName, url: res.fileName });
+  emit("update:modelValue", listToString(fileList.value));
+  proxy.$modal.closeLoading();
+}
+
+// 涓婁紶鍓峫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);
+    }
+    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;
+    }
+  }
+  proxy.$modal.loading("涓婁紶涓�");
+}
+
+// 鏂囦欢涓暟瓒呭嚭
+function handleExceed() {
+  proxy.$modal.msgError(`涓婁紶鏂囦欢鏁伴噺涓嶈兘瓒呰繃 ${props.limit} 涓�!`);
+}
+
+// 涓婁紶澶辫触
+function handleUploadError() {
+  proxy.$modal.msgError("涓婁紶澶辫触");
+  proxy.$modal.closeLoading();
+}
+
+// 棰勮
+function handlePictureCardPreview(file) {
+  dialogImageUrl.value = file.url;
+  dialogVisible.value = true;
+}
+
+// 瀵硅薄杞垚鎸囧畾瀛楃涓插垎闅�
+function listToString(list, separator) {
+  let strs = "";
+  separator = separator || ",";
+  for (let i in list) {
+    strs += list[i].url.replace(baseUrl, "") + separator;
+  }
+  return strs != "" ? strs.substr(0, strs.length - 1) : "";
+}
+</script>
+
+<style scoped lang="scss">
+// .el-upload--picture-card 鎺у埗鍔犲彿閮ㄥ垎
+:deep(.hide .el-upload--picture-card) {
+  display: none;
+}
+// 鍘绘帀鍔ㄧ敾鏁堟灉
+:deep(.el-list-enter-active),
+:deep(.el-list-leave-active) {
+  transition: all 0s;
+}
+:deep(.el-list-enter, .el-list-leave-active) {
+  opacity: 0;
+  transform: translateY(0);
+}
+</style>
\ No newline at end of file
diff --git a/src/main.js b/src/main.js
index 91fdbc5..9398b0c 100644
--- a/src/main.js
+++ b/src/main.js
@@ -31,6 +31,8 @@
 import Pagination from '@/components/Pagination'
 // 鑷畾涔夎〃鏍煎伐鍏风粍浠�
 import RightToolbar from '@/components/RightToolbar'
+// 鍥剧墖涓婁紶缁勪欢
+import ImageUpload from "@/components/ImageUpload"
 // 鑷畾涔夋爲閫夋嫨缁勪欢
 import TreeSelect from '@/components/TreeSelect'
 // 瀛楀吀鏍囩缁勪欢
@@ -51,6 +53,7 @@
 app.component('DictTag', DictTag)
 app.component('Pagination', Pagination)
 app.component('TreeSelect', TreeSelect)
+app.component('ImageUpload', ImageUpload)
 app.component('RightToolbar', RightToolbar)
 
 app.use(router)

--
Gitblit v1.9.3