el-upload附件上传组件

效果图: 

 

 组件引用

<FileUpload v-model="form.fileList"></FileUpload>

组件代码

<template>
  <div class="upload-file">
    <el-upload
      v-if="!isView"
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :on-remove="handleDelete"
      :show-file-list="false"
      :headers="headers"
      class="upload-file-uploader"
      ref="fileUpload"
      :accept="accetpType"
    >
      <!-- 上传按钮 -->
      <!-- <el-button size="mini" type="primary">选取文件</el-button> -->
      <div v-if="!isView">
        <img src="图片地址" alt="" />
      </div>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        附件限
        <b style="color: #f56c6c">{{ limit }}</b>
        个
        <span v-if="limit > 1">
          (含
          <b style="color: #f56c6c">{{ limit }}</b>
          个)
        </span>
        <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-upload>

    <!-- 文件列表 -->
    <transition-group
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul"
    >
      <li
        class="el-upload-list__item ele-upload-list__item-content"
        v-for="(file, index) in fileList"
        :key="index"
      >
        <span class="el-icon-document" @click="downFile(file)">
          {{ file.fileName }}
        </span>
        <div class="ele-upload-list__item-content-action" v-if="!isView">
          <el-link :underline="false" @click="handleDelete(index)" type="danger"
            >删除</el-link
          >
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { Message } from "element-ui";

export default {
  name: "FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 10,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf", "zip",'png', 'jpg', 'jpeg'],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/base/newUpload", // 上传文件服务器地址
      accetpType: "",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      size: 0,
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val && val.length > 0) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            // if (typeof item === "string") {
            //   item = { name: item, url: item };
            // }
            let tempArr = { fileName: item.fileName, filePath: item.filePath };
            return tempArr;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      if (this.isView) {
        return !this.isView;
      } else {
        return this.isShowTip && (this.fileType || this.fileSize);
      }
    },
  },
  methods: {
    downFile(file) {
      // down.fileService(file.filePath, file.fileName);
      // window.open(file.filePath)
      let a = document.createElement('a')
      a.href = file.filePath;
      a.download = file.fileName;
      a.target="_blank";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split(".");
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          Message.error(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          Message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        } else {
          this.size = file.size;
        }
      }
      // this.$modal.loading("正在上传文件,请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      Message.error(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      Message.error("上传文件失败,请重试");
      // this.$modal.closeLoading();
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        let temp = res.data;
        this.uploadList.push({
          fileName: temp.originalFilename,
          filePath: temp.url,
          fileSize: this.size,
        });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        // this.$modal.closeLoading();
        Message.error(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除文件
    handleDelete(index) {
      this.$refs.fileUpload.uploadFiles.splice(index, 1);
      this.fileList.splice(index, 1);
      this.$emit("input", this.fileList);
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.fileList);
        // this.$modal.closeLoading();
      }
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },
  },
  mounted() {
    let temp = this.fileType.map((item) => "." + item);
    this.accetpType = temp.join(",");
  },
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
.el-icon-document {
  display: block;
  padding: 9px 4px;
  cursor: pointer;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值