heyujie
2021-12-07 4ff29e301de38488db0ff04f0209c99e37cf30b4
src/pages/library/components/upload.vue
@@ -1,6 +1,6 @@
<template>
  <span class="upload-content pr">
    <el-button
    <!-- <el-button
      type="primary"
      :loading="upLoadLoading"
      :size="uploadBtnSize"
@@ -9,7 +9,12 @@
    >
      <i :class="uploadBtnIcon"></i>
      &nbsp;&nbsp;{{uploadBtntext}}
    </el-button>
    </el-button> -->
    <span
      class="iconfont iconfont-wrap iconshangchuantupian-09"
      @click="uploadStart"
      :loading="upLoadLoading"
    ></span>
    <div class="upload-progress" v-if="isShowProgress">
      <b-progress
        variant="warning"
@@ -30,7 +35,10 @@
        @dragenter="dragenter($event)"
        @dragleave="dragleave($event)"
      >
        <i class="el-icon-upload text-primary" style="color:rgb(61, 104, 225)"></i>
        <i
          class="el-icon-upload text-primary"
          style="color: rgb(61, 104, 225)"
        ></i>
        <div class="el-upload__text" style="color:#babbbc!important">
          将文件拖到此处,或
          <em class="text-primary cursor-pointer">点击上传</em>
@@ -38,68 +46,75 @@
        <div
          class="el-upload__tip text-light"
          style="color:#babbbc!important"
        >{{limitTypes?`只能上传${limitTypes}文件`:''}}{{limitSize?` 文件大小不超过${limitSize}`:''}}</div>
        >
          {{ limitTypes ? `只能上传${limitTypes}文件` : ""
          }}{{ limitSize ? ` 文件大小不超过${limitSize}` : "" }}
      </div>
    </div>
    <div class="upload-model" v-show="isShowBox" @click="isShowBox=false"></div>
    </div>
    <div
      class="upload-model"
      v-show="isShowBox"
      @click="isShowBox = false"
    ></div>
  </span>
</template>
<script>
import axios from 'axios'
import { guid } from '@/scripts/util.js'
import axios from "axios";
import { guid } from "@/scripts/util.js";
export default {
  name: 'upload',
  name: "upload",
  props: {
    /* 上传控件列表是否删除功能 */
    isDelFile: {
      default: true,
      type: Boolean
      type: Boolean,
    },
    /* 类型限制(后缀名,分隔) 传入示例'.png,.jpg'  不限制为 '' */
    limitTypes: {
      default: '',
      type: String
      default: "",
      type: String,
    },
    /* 文件大小限制 传入示例'1M' 单位支持G、M、K、B 无单位按B计算  不限制为 '' */
    limitSize: {
      default: '5M',
      type: String
      default: "5M",
      type: String,
    },
    /* 上传按钮文字 */
    uploadBtntext: {
      default: '上传',
      type: String
      default: "上传",
      type: String,
    },
    /* 上传按钮icon */
    uploadBtnIcon: {
      default: 'ion ion-md-cloud-upload',
      type: String
      default: "ion ion-md-cloud-upload",
      type: String,
    },
    uploadBtnSize: {
      default: '',
      type: String
      default: "",
      type: String,
    },
    uploadBtnStyle: {
      default: '',
      type: String
      default: "",
      type: String,
    },
    uploadBtnClass: {
      default: 'btn btn-primary',
      type: String
      default: "btn btn-primary",
      type: String,
    },
    isShowProgress: {
      default: false,
      type: Boolean
      type: Boolean,
    },
    isDrag: {
      default: false,
      type: Boolean
      type: Boolean,
    },
    idJson: {
      default: null,
      type: Object
    }
      type: Object,
    },
    /**
     * 上传组件回值方法
     * @description 上传组件回值方法
@@ -109,245 +124,244 @@
  data() {
    return {
      isShowBox: false,
      drag_class: '',
      drag_class: "",
      fileList: [],
      erFileList: [],
      suFileList: [],
      fileIds: [],
      upLoadLoading: false,
      showProgress: false,
      progressValue: 0
    }
      progressValue: 0,
    };
  },
  computed: {},
  methods: {
    islimitTypes(fileObj) {
      if (this.limitTypes === '') {
        return 'success'
      if (this.limitTypes === "") {
        return "success";
      }
      if (
        this.limitTypes.indexOf(
          fileObj.name.toLowerCase().replace(/^.+\./, '')
          fileObj.name.toLowerCase().replace(/^.+\./, "")
        ) === -1
      ) {
        const msg = {
          type: 'error',
          errorType: '上传类型错误',
          type: "error",
          errorType: "上传类型错误",
          message:
            /* ${fileObj && fileObj.name ? '“' + fileObj.name + '”' : ''} */
            `上传文件必须是${this.limitTypes},请您核查`
        }
            `上传文件必须是${this.limitTypes},请您核查`,
        };
        // this.$notify(msg)
        return msg
        return msg;
      }
      return 'success'
      return "success";
    },
    islimitSize(fileObj) {
      if (this.limitSize === '') {
        return 'success'
      if (this.limitSize === "") {
        return "success";
      }
      let size = 0
      if (this.limitSize.indexOf('G') !== -1) {
        size = this.limitSize.replace('G', '') * 1024 * 1024 * 1024
      } else if (this.limitSize.indexOf('M') !== -1) {
        size = this.limitSize.replace('M', '') * 1024 * 1024
      } else if (this.limitSize.indexOf('K') !== -1) {
        size = this.limitSize.replace('K', '') * 1024
      } else if (this.limitSize.indexOf('B') !== -1) {
        size = this.limitSize.replace('B', '')
      let size = 0;
      if (this.limitSize.indexOf("G") !== -1) {
        size = this.limitSize.replace("G", "") * 1024 * 1024 * 1024;
      } else if (this.limitSize.indexOf("M") !== -1) {
        size = this.limitSize.replace("M", "") * 1024 * 1024;
      } else if (this.limitSize.indexOf("K") !== -1) {
        size = this.limitSize.replace("K", "") * 1024;
      } else if (this.limitSize.indexOf("B") !== -1) {
        size = this.limitSize.replace("B", "");
      } else {
        size = this.limitSize
        size = this.limitSize;
      }
      if (size < fileObj.size) {
        const msg = {
          type: 'error',
          errorType: '上传大小错误',
          type: "error",
          errorType: "上传大小错误",
          message:
            `${
            fileObj && fileObj.name ? '“' + fileObj.name + '”' : ''
            }必须小于` + this.limitSize
        }
              fileObj && fileObj.name ? "“" + fileObj.name + "”" : ""
            }必须小于` + this.limitSize,
        };
        // this.$notify(msg)
        return msg
        return msg;
      }
      return 'success'
      return "success";
    },
    uploadStart(type) {
      this.$refs.fileInput.value = ''
      this.fileList = []
      this.erFileList = []
      this.suFileList = []
      if (this.isDrag && type !== 'fileInput') {
        this.isShowBox = !this.isShowBox
      this.$refs.fileInput.value = "";
      this.fileList = [];
      this.erFileList = [];
      this.suFileList = [];
      if (this.isDrag && type !== "fileInput") {
        this.isShowBox = !this.isShowBox;
      } else {
        this.$refs.fileInput.click()
        this.$refs.fileInput.click();
      }
    },
    /* 点击上传 */
    clickUpLoad(e) {
      if (e.target && e.target.files) {
        this.handleUpLoad(e.target.files)
        this.handleUpLoad(e.target.files);
      }
    },
    // 上传附件
    handleUpLoad(files) {
      // 判断是否选择底库
      // console.log(this.idJson, 'upload this.idJson')
      if (this.idJson.tableId === undefined || this.idJson.tableId === '') {
      if (this.idJson.tableId === undefined || this.idJson.tableId === "") {
        this.$notify({
          type: 'error',
          message: '请先选择一个底库!'
        })
        return
          type: "error",
          message: "请先选择一个底库!",
        });
        return;
      }
      /* 拿到上传文件 */
      if (files.length === 0) {
        return false
        return false;
      }
      this.fileList = [...files]
      this.fileList = [...files];
      /* 重置进度条 */
      this.showProgress = true
      this.progressValue = 0
      this.showProgress = true;
      this.progressValue = 0;
      /* 开启上传按钮loding */
      this.upLoadLoading = true
      this.upLoadLoading = true;
      /* 创建FormData文件对象 */
      const fd = new FormData()
      const fd = new FormData();
      this.fileList.map((file, index) => {
        /* 文件校验 start */
        const islimitTypes = this.islimitTypes(file)
        const islimitSize = this.islimitSize(file)
        if (islimitTypes !== 'success') {
        const islimitTypes = this.islimitTypes(file);
        const islimitSize = this.islimitSize(file);
        if (islimitTypes !== "success") {
          this.erFileList.push({
            uuId: guid(),
            file: file,
            errorMsg: islimitTypes
          })
          return false
            errorMsg: islimitTypes,
          });
          return false;
        }
        if (islimitSize !== 'success') {
        if (islimitSize !== "success") {
          this.erFileList.push({
            uuId: guid(),
            file: file,
            errorMsg: islimitSize
          })
          return false
            errorMsg: islimitSize,
          });
          return false;
        }
        this.suFileList.push(file)
        this.suFileList.push(file);
        /* 文件校验 end */
        // fd.append('files' + index, file)
        fd.append('files', file)
      })
        fd.append("files", file);
      });
      // fd.append('files', this.suFileList)
      /* 添加tableId  start */
      if (this.idJson && this.idJson.tableId) {
        console.log(this.idJson, 'upload this.idJson')
        fd.append('tableId', this.idJson.tableId)
        console.log(this.idJson, "upload this.idJson");
        fd.append("tableId", this.idJson.tableId);
      }
      /* 添加orgId officeId  end */
      // fd.append('fileSource', 'FDFS')
      if (this.fileList.length > this.erFileList.length) {
        this.uploadServer(fd)
        this.uploadServer(fd);
      } else {
        /* 回调传值 */
        this.$emit('addFilesBaBackFN', {
        this.$emit("addFilesBaBackFN", {
          suFileList: this.suFileList,
          erFileList: this.erFileList,
          fileList: this.fileList,
          result: null
        })
          result: null,
        });
        /* 结束上传按钮loding */
        this.upLoadLoading = false
        this.upLoadLoading = false;
        /* 隐藏拖拽框 */
        this.isShowBox = false
        this.isShowBox = false;
      }
    },
    async uploadServer(fd) {
      // this.$store.commit('HANDLE_LOADING_OPEN')
      const token = JSON.parse(
        sessionStorage.getItem('loginedInfo')
      ).access_token
      const token = JSON.parse(sessionStorage.getItem("loginedInfo"))
        .access_token;
      try {
        let res = await axios({
          method: 'post',
          method: "post",
          url: `/data/api-v/dbperson/moreFileUpload`,//?access_token=${token}
          data: fd,
          name: 'files',
          name: "files",
          headers: {
            Authorization: token
            Authorization: token,
          },
          onUploadProgress: progressEvent => {
          onUploadProgress: (progressEvent) => {
            if (
              this.isShowProgress &&
              progressEvent.loaded &&
              progressEvent.total
            ) {
              this.progressValue =
                (progressEvent.loaded / progressEvent.total) * 100
                (progressEvent.loaded / progressEvent.total) * 100;
            }
          }
        })
          },
        });
        if (res && res.data) {
          const result = res.data
          const result = res.data;
          // this.$notify({
          //   type: result && result.success ? 'success' : 'error',
          //   message: result.msg
          // })
          this.progressValue = 0
          this.showProgress = false
          this.$emit('successFN', result)
          this.progressValue = 0;
          this.showProgress = false;
          this.$emit("successFN", result);
        }
      } catch (error) {
        this.progressValue = 0
        this.showProgress = false
        const errorArr = this.suFileList.map(file => {
        this.progressValue = 0;
        this.showProgress = false;
        const errorArr = this.suFileList.map((file) => {
          return {
            uuId: guid(),
            file: file,
            errorMsg: {
              type: 'error',
              errorType: '上传服务器错误',
              message: '上传服务器错误'
            }
          }
        })
        this.erFileList = [...this.erFileList, ...errorArr]
              type: "error",
              errorType: "上传服务器错误",
              message: "上传服务器错误",
            },
          };
        });
        this.erFileList = [...this.erFileList, ...errorArr];
        /* 回调传值 */
        this.$emit('addFilesBaBackFN', {
        this.$emit("addFilesBaBackFN", {
          suFileList: [],
          erFileList: this.erFileList,
          fileList: this.fileList,
          result: error
        })
          result: error,
        });
      }
      //this.$store.commit('HANDLE_LOADING_CLOSE')
      /* 结束上传按钮loding */
      this.upLoadLoading = false
      this.upLoadLoading = false;
      /* 隐藏拖拽框 */
      this.isShowBox = false
      this.isShowBox = false;
    },
    /* 拖拽函数 start */
    dragleave(el) {
      this.drag_class = ''
      el.stopPropagation()
      el.preventDefault()
      this.drag_class = "";
      el.stopPropagation();
      el.preventDefault();
    },
    dragenter(el) {
      this.drag_class = 'active'
      el.stopPropagation()
      el.preventDefault()
      this.drag_class = "active";
      el.stopPropagation();
      el.preventDefault();
    },
    dragover(el) {
      this.drag_class = 'active'
      el.stopPropagation()
      el.preventDefault()
      this.drag_class = "active";
      el.stopPropagation();
      el.preventDefault();
    },
    drop(el) {
      el.stopPropagation()
      el.preventDefault()
      el.stopPropagation();
      el.preventDefault();
      if (el.dataTransfer && el.dataTransfer.files) {
        this.handleUpLoad(el.dataTransfer.files)
        this.handleUpLoad(el.dataTransfer.files);
      }
    }
    },
    /* 拖拽函数 end */
  },
  created() { },
@@ -355,16 +369,16 @@
    progressValue(newVal, oldVal) {
      if (newVal !== oldVal && newVal >= 100) {
        setTimeout(() => {
          this.showProgress = false
          this.progressValue = 0
        }, 1500)
          this.showProgress = false;
          this.progressValue = 0;
        }, 1500);
      }
    }
    },
  },
  components: {
    //LaddaBtn
  }
}
  },
};
</script>
<style lang="scss" scoped>