<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
<el-checkbox-group v-model="checkList" style="margin: 0 0 10px 10px;">
<el-checkbox label="A">apple</el-checkbox>
<el-checkbox label="B">boy</el-checkbox>
<el-checkbox label="C">cat</el-checkbox>
<el-checkbox label="D">dog</el-checkbox>
</el-checkbox-group>
<el-upload style="margin: 10px 0 10px 30px;"
ref="upload"
accept=".xls"
:action="uploadURL"
:on-error="uploadError"
:on-success="uploadSuccess"
:auto-upload="false"
name="uploadedFile"
:data="queryParams">
<el-button type="primary" icon="el-icon-circle-plus-outline" slot="trigger">
导入xls文件
</el-button>
</el-upload>
<div class="buttons" style="margin: 10px 0 0 25px;">
<el-button type="success" @click="submitUpload">提交</el-button>
<el-button type="danger" @click="reset">重置</el-button>
</div>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script type="text/javascript">
new Vue({
el: '#app',
data() {
return {
checkList: [],
uploadURL: "",
queryParams: {}
}
},
created:function(){
},
methods: {
uploadError(err, file, fileList) {
// 上传失败
this.$message.error(err);
this.reset();
},
uploadSuccess(response, file, fileList) {
// 上传成功
console.log(response);
console.log(file);
console.log(fileList);
this.reset();
},
submitUpload() {
this.$set(this.queryParams, "params", this.checkList.toString());
this.$refs.upload.submit();
},
reset() {
// 重置
// 清空多选框
this.checkList = [];
// 清空上传列表
this.$refs.upload.clearFiles();
}
}
})
</script>
</html>
为<el-upload>
标签设置:auto-upload="false"
属性防止选取文件后立即进行上传。
设置:action="uploadURL"
属性指定上传的地址。
accept=".xls"
属性用于限定接受上传的文件类型。
name="uploadedFile"
属性用于制定上传的文件字段名,即上传的文件的 key。
:data="queryParams"
属性用于在上传时添加附带的额外参数,需赋值一个 object 对象。
通过调用this.$refs.upload.submit()
方法便可实现上传文件,:on-error="uploadError"
和:on-success="uploadSuccess"
分别是文件上传失败时(网络或者服务器端以及其他原因导致上传失败)和文件上传成功时的钩子函数,它们都有三个参数,function(response, file, fileList)
,分别是服务端返回的信息 response 、上传的文件以及上传的文件列表。
使用this.$refs.upload.clearFiles()
方法可以清空文件上传列表。