Bootstrap

vue实现导入文件功能

今天有个需求是导入xlsx文件,我想了想就写了一个这样的代码,提供参考一下

<template>
 <div class="healthy-doc"> 
    <div class="file-upload" style="padding-left:10px">
         <input type="file" ref="fileInputs" @change="onFileChanges" class="file-input">
         <el-button type="primary" round size="mini">导&nbsp;入</el-button>
    </div>
 </div>
<template>
<script>
export default {
 data () {
   return {

   }
},
 methods:{
     //文件上传
     onFileChanges(){
        //定义上传封装的对象
        const formData = new FormData();
        //获取上传的问file
        const file = this.$refs.fileInputs.files[0];
        //之所以是file 是以为后端接受的就是file 所以这个file一点的和后端的保持一直
        formData.append('file',file);
        //这个是就是一个上传等待的动画,这个你可以根据你自己的需要来修改
        const loading = this.$loading({
            lock: true,
            text: '请等待',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        console.log(formData,'formData');
        //这个是上传的路径 其中dashboard/importDataFile 这个是我自己封装的路径,你可以写你的                
        //上传路径
        this.$store.dispatch("dashboard/importDataFile",formData).then(res=>{
            console.log(res,'66666');
            this.$message({
                message: '导入成功',
                type: 'warning'
            });
            //这个是刷新页面
            location.reload();
            //这个是查询的方法,你可以加上你的,这个也可以去掉(都行,建议测试的去掉)
            this.getPatientList();
            setTimeout(() => {
                //关闭动画
                loading.close();
            }, 2000);   
        })
     },

}


}
</script>
<style lang="scss" scoped>
   .healthy-doc {
     padding: 10px 15px;
     width: 100%;
   }
   .file-upload {
     position: relative;
     display: inline-block;
   }
  .file-input {
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
    width:100px;
  }
</style>

以上代码你拿过来就能直接用

;