vue 中 js写上传excel表格

在页面创建一个选择文件的按钮,通过按钮点击触发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>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值