1. 首先是模板()
<template>
<div class="import-list">
<el-button class="import-button" @click="uploadFiles">
<i class="icon"></i>
导入公司{{title}}
</el-button>
<el-dialog
class="dialog-box"
title="上传"
width="40%"
:visible.sync="uploadShowDialog">
<el-upload
class="upload-demo"
ref="upload"
action="#"
:multiple="false"
:show-file-list="true"
:before-upload="beforeUpload"
:http-request="uploadHttpRequest"
:file-list="fileList"
:on-change="handleUploadChange">
<div class="choose-file" slot="trigger">
<i class="icon"></i>
选取Excel格式文件
</div>
<div
slot="tip"
class="el-upload-tip">
只能上传.xls、.xlsx文件,且不超过1M
</div>
</el-upload>
<span slot="footer">
<el-button
@click="submitUpload"
type="primary"
:loading="uploadLoading">
确定导入
</el-button>
<span @click="uploadShowDialog=false" class="cancelDialog">
取消
</span>
</span>
</el-dialog>
</div>
</template>
2.data中
data() {
return {
//加载动画
uploadLoading: false,
//上传的文件列表
fileList: [],
//控制弹出框显示与否
uploadShowDialog: false,
//上传地址
uploadURL: '',
//loading加载中
downloadLoading: '',
}
},
3. methods中的方法
uploadFiles(){
this.uploadLoading = false;
this.fileList = [];
this.uploadShowDialog = true;
setTimeout( () => {
//清空已上传的文件列表
this.$refs.upload.clearFiles();
}, 100);
},
// 限制文件上传的个数只有一个,获取上传列表的最后一个
handleUploadChange(file, fileList) {
if (fileList.length > 0) {
// 这一步,是展示最后一次选择的文件
this.fileList = [fileList[fileList.length - 1]]; }
},
// 上传文件之前,先判断文件后缀和大小
beforeUpload(file) {
//截取文件后缀名
const fileName = file.name.substring(file.name.lastIndexOf('.'));
if(fileName.toLowerCase()!='.xls' &&fileName.toLowerCase() !='.xlsx')
{
this.$message.error('文件必须为.xls或xlsx类型');
this.fileList = [];
return false;
};
//读取文件大小
var fileSize = file.size;
console.log(fileSize);
if(fileSize > 1048576){
this.uploadShowDialog = false;
this.$message({
type:'error',
showClose:true,
duration:3000,
message:'文件不能大于1M!'
});
return false;
}
},
// 覆盖element的默认上传文件
uploadHttpRequest(data) { //data中有action属性
console.log(data);
console.log('上传地址为:' + this.uploadURL);
},
//点击确定上传按钮
submitUpload() {
//loading加载中,通过this.downloadLoading.close()可关闭
this.downloadLoading = this.$loading({
lock:true,
text: '数据导入中...',
color: '#0183FF',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.3)'
});
if(this.fileList.length === 0) {
this.$message({
type:'error',
showClose:true,
duration:3000,
message:'请选择要上传的文件'
});
return false;
}
//调接口上传
let formData = new FormData();
//控制台打印file,找到要上传的file,图中.raw
formData.append("file", file[0].raw);
//注:formData中的数据不能直接打印,需要用到get方法得到
console.log(formData.get('file'));
//ajax、axios等方法上传,这里不细说明
},
参考:https://www.cnblogs.com/zhuqi7758258/articles/10643181.html