vue+elementui 实现上传文件/导入文件的功能
1. 上传组件
<el-form-item label="上传文件:">
<el-upload
action=""
:file-list="fileList"
:show-file-list="false"
:http-request="handUpLoad"
drag
:limit="1"
:accept="'.xls, .xlsx'"
>
<i class="el-icon-upload" />
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>
<ul class="downloadFile">
<li v-for="(val, index) in fileList" :key="index">
<a class="el-upload-list__item-name" href="javascript:;"><i class="el-icon-document" />{{ val.fileName }}</a>
<i class="el-icon-close" @click="handleFileRemove(val)" />
</li>
<li v-show="fileLoading"><i class="loading el-icon-loading" /> </li>
</ul>
</el-form-item>
2. data中的数据
data() {
return {
fileList: [],
fileLoading: false,
fileobj: ''
}
}
3. methods中的方法
① 选择文件
handUpLoad(fileobj) {
this.fileobj = fileobj
this.fileList = [{
fileName: fileobj.file.name,
fileSize: fileobj.file.size
}]
}
② 点击确定,调用接口上传文件
submit() {
if (this.fileList.length === 0) {
this.$message({
message: '请先上传文件',
type: 'warning'
})
return
}
const param = new FormData()
param.append('file', this.fileobj.file)
fileImport(param).then(res => {
this.$message({
type: 'success',
message: '上传成功'
})
}).catch(err => {
this.$message.error(err)
}).finally(() => {
this.$emit('refresh')
})
}
③ 删除文件
handleFileRemove() {
this.fileList = []
}