index.vue 1.77 KB
<style scoped>
.file-icon {
  color: #8c8c8c;
}
.file-link {
  color: #2f54eb;
  display: flex;
  align-items: center;
}
.file-name {
  padding: 0px 15px;
}
.file-name:hover {
  color: #69c0ff;
}
.file-delete {
  color: #d9d9d9;
}
.file-delete:hover {
  color: #f5222d;
}
</style>

<template>
  <el-upload
    :action="uploadURL"
    :show-file-list="false"
    :headers="headers"
    :data="param"
    :on-success="handleSuccess"
    :before-upload="beforeUpload"
    style="width: 100%;"
  >
    <span v-if="value" class="file-link" @click.stop>
      <i class="iconfont icon-attachment file-icon"></i>
      <a class="file-name" :href="value" target="_blank">点击下载</a>
      <i class="iconfont icon-close file-delete" title="点击删除" @click="deleteFile"></i>
    </span>
    <el-button v-else size="small" type="primary">点击上传</el-button>
  </el-upload>
</template>

<script>
import { getToken } from '@/utils/auth';

const uploadURL = process.env.VUE_APP_API_FILE_UP;

export default {
  props: {
    value: String,
    param: {
      type: Object,
      default() {
        return {};
      }
    },
    maxMB: {
      type: Number,
      default: 2
    }
  },
  name: 'FileUpload',
  data() {
    return {
      headers: { 'authorization': `Bearer ${getToken()}` },
      uploadURL: uploadURL,
    };
  },
  methods: {
    handleSuccess(response = {}, file, fileList) {
      const { result = [] } = response;
      const url = result[0];
      this.$emit('input', url);
    },
    beforeUpload(file) {
      const isLtMaxMB = file.size / 1024 / 1024 < this.maxMB;
      if (!isLtMaxMB) {
        this.$message.error(`上传附件大小不能超过 ${this.maxMB}MB!`);
      }
      return isLtMaxMB;
    },
    deleteFile() {
      this.$emit('input', undefined);
    }
  }
}
</script>