在页面创建一个选择文件的按钮,通过按钮点击触发chooseFile函数来模拟input[type=’file’]点击选择文件事件。监听input[type=’file’]的onchange事件,来获取选中文件对象,再通过点击确认导入按钮触发upFile函数来实现文件的异步上传。复制大佬的代码,只是存下来方便以后查看大佬的帖子点我

<template>
<div class="upload-panel">
   <div class="panel-heading">考勤导入</div>
   <div class="panel-body">
      <p><strong>注意事项:</strong><br>1、导入文件格式:.xls,.xlsx<br>2、文件命名规则“年月名”,如:“201705运维部考勤”></a></p>
      <p style="margin-top:10px;"><strong>考勤导入:</strong><a class="btn btn-primary btn-xs " @click="chooseFile">选择文件</a></p>
      <p>已选择文件:<em style="color:red; font-style:normal;">{{attence}}</em></p><p>{{info}}</p>
      <input type="file" style="display:none" name="attence"  @change="changeFile($event)" ref="attenceInput" />
   </div>
   <div class="panel-footer">
      <a class="btn btn-primary btn-md" @click="upFile">确认导入</a>
   </div>
</div>
</template>
<script>
   export default {
     name: 'Upload',
     data () {
       return {
         attence: '',
         attenceFile: {}
       }
     },
     methods: {
       chooseFile () {
         this.$refs.attenceInput.click();
       },
       changeFile (e) {
         this.attence = e.target.files[0].name;
         this.attenceFile = e.target.files[0];
       },
       upFile () {
         let filename = this.attenceFile.name;
         let arr = filename.split('.');
         if (arr[1] !== 'xls' && arr[1] !== 'xlsx') {
           this.$toast.center('文件格式错误!');
           return;
         }
         let fileData = new window.FormData();
         fileData.append('file', this.attenceFile)
     let xhr = new window.XMLHttpRequest();
     xhr.open('POST', 'http://localhost:999/base/upload', true);
     xhr.send(fileData);
     xhr.onreadystatechange = () => {
       if (xhr.readyState === 4) {
        if (xhr.status === 200) {
         let response = JSON.parse(xhr.response)
         this.$toast.center(response.message)
        } else {
         let error = this.$emit('upload-error', xhr)
         if (error !== false) {
          this.$toast.center(xhr.statusText)
         }
        }
       }
     }
       }
     }
   }
</script>
Logo

前往低代码交流专区

更多推荐