恰逢项目中要实现excel表格上传,度娘甚久,得此一文,留之。 原文:https://blog.csdn.net/qq_36718999/article/details/95387542
需求
vue-cli 搭建前端项目,并使用element-ui实现本地excel表格上传。 (1) 限制上传文件只能是 xls、xlsx格式; (2) 限制上传文件大小不能超过 2MB!
图示
代码实现
<el-form
ref="newUploadForm"
:model="newUploadForm"
:rules="formRules"
label-width="140px"
label-position="right">
<el-row class="mb-4">
<el-col :span="24">
<el-form-item label="文件密码" prop="password" >
<el-input v-model="newUploadForm.password" clearable
placeholder="文件密码(至少6位字母或数字)" ></el-input>
</el-form-item>
</el-col>
</el-row>
<el-row >
<el-col :span="19">
<el-form-item label="上传文件" prop="fileName">
<el-input v-model="fileName"
:readonly='true'
placeholder="文件名"
style="width:510px;"></el-input>
</el-form-item>
</el-col>
<el-col :span="4">
<el-upload
class="upload-demo"
ref="upload"
action="doUpload"
:limit="1"
:file-list="fileList"
:before-upload="beforeUpload"
>
<el-button slot="trigger" type="primary" plain>选取文件</el-button>
<!-- <div slot="tip" class="el-upload__tip">只能上传excel文件,且不超过100MB</div>
<div slot="tip" class="el-upload-list__item-name">{{fileName}}</div> -->
</el-upload>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<div class="btns-center mb-48 pt-48">
<el-button @click="handleClose">取 消</el-button>
<el-button type="primary"
@click="submitUpload()">确 定</el-button>
</div>
</el-col>
</el-row>
</el-form>
export default {
data() {
return {
fileList:[],
fileName:'',
newUploadForm:{
password:'',
fileName:''
},
formRules:{ // 表单 校验
password:{required:true, trigger: 'blur',validator: validateFilePassword},
},
}
},
methods:{
beforeUpload(file){ // 上传前 文件校验
this.files = file;
const extension = file.name.split('.')[1] === 'xls'
const extension2 = file.name.split('.')[1] === 'xlsx'
const isLt2M = file.size / 1024 / 1024 < 2
if (!extension && !extension2) {
this.$message.warning('上传文件只能是 xls、xlsx格式!')
return
}
if (!isLt2M) {
this.$message.warning('上传文件大小不能超过 2MB!')
return
}
this.fileName = file.name;
return false // 返回false不会自动上传
},
submitUpload() { // 确认上传
this.$refs['newUploadForm'].validate(valid => { // 是否通过 表单验证
if(valid){
if(this.fileName == ""){
this.$message({
message:'请选择要上传的文件!',
type:'warning',
showClose:true
})
return false;
}
let fileFormData = new FormData();
fileFormData.append('file', this.files, this.fileName); // 上传的文件
fileFormData.append('period', this.newUploadForm.password); // 文件密码
fileFormData.append('fileName', this.newUploadForm.fileName); // 文件名
uploadEmployee(fileFormData).then(res => { // 上传请求
this.fileName = '';
// console.log(res)
if(res.code == 200){
}else{
}
}).catch(err => {
this.fileName = '';
console.log('err')
})
}else{
this.$message({
type:'warning',
message:'新增条件有误!',
showClose:true
})
}
})
},
handleClose() {
this.fileName = '';
}
}
}
// 上传接口
export function uploadEmployee(params) {
return request({
url: '/apis/upload/uploadEmployee',
method: 'post',
headers: {
'Content-Type': 'multipart/form-data'
},
processData: false,
data:params
})
}