<template>
  <div>
      <el-upload
        ref="upload"
        :limit="1"
        :action="action"
        :auto-upload="true"
        :show-file-list="false"
        :headers="headers"
        :before-upload="uploadBefore"
        :on-success="uploadSuccess"
        :on-change="handleChange"
      >
        <span style="float: left;">
          <el-button plain type="primary" size="small" icon="el-icon-plus">
            选择文件
          </el-button>
        </span>

        <span style="margin-left: 20px;">
          {{filename||''}}
        </span>
        <br>
      </el-upload>
  </div>
</template>


<script>
import { authDB } from '@/db'

export default {
  name: 'UploadFile',
  components:{},
  data() {
    return {
      action: '/api/artical/uploadFile',
      headers:{
        'x-token': authDB.get('token'),
        'x-user-id': authDB.get('uid')
      },
      filename:''
    }
  },
  methods: {
    uploadFile() {
      this.$refs.upload.submit();
    },
    uploadBefore(file) {
      const maxSize = file.size / 1024 / 1024 < 10;
      if (!maxSize) {
        this.$message.error('每个文件最大10M');
      }
      return maxSize;
    },
    uploadSuccess(res) {
      const { data } = res;
      if (data) {
        this.$emit('onFinish', data.filename);
      }
    },
    handleChange(file) {
      if (file.status == 'ready') {
        this.filename = file.name;
      }
    },

  }
}
</script>

<style lang="scss" scoped>

</style>
