引言
在一次项目中需要进行excel文件的上传,在此文章中只介绍element-ui中el-upload组件,主要是在于后端交互时使用forData对象形式传输
<el-upload
ref="upload" action
:limit="1"
:auto-upload="false"
:before-remove="beforeRemove"
@change="handleUpload"
@exceed="handlExceed"
>
<el-button slot="trigger" round>选区文件</el-button>
<div slot="tip">只能上传excel文件</div>
</el-upload>
data() {
return {
fileList: []
}
}
methods: {
handleUpload(file, fileList) {
if (this.judgeFileType(file.raw)) {
this.fileList = fileList
}
},
judgeFileType(file) {
if (/\.xls|.xlsx$/.test(file.name)) {
return true
} else {
this.$message.error('请上传excel文件')
return false
}
},
handleExceed(file, fileList) {
this.$message.error('最多只能上传一个文件')
}
}
创建一个formData,并将文件插入进去
const formData = new FormData()
formData.append('file', this.fileList[0].raw)