html:
<div>
<el-card class="box-card">
<el-upload
ref="upload"
accept=".xls,.xlsx"
action="#"
:auto-upload="false"
:multiple="false"
:file-list="fileList"
:before-upload="beforeUpload"
:http-request="uploadHttpRequest"
:on-remove="fileRemove"
:on-change="fileChange"
>
<img class="upImg" src="../../style/img/up.png" alt="" />
<el-button class="buttonUp" type="primary">上传excel</el-button>
<div class="el-upload__text">或者拖放一个文件</div>
</el-upload>
</el-card>
<div class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</div>
<div><el-button style="width: 450px; margin: 20px auto; padding: 15px" type="primary" @click="submitUpload">确认上传</el-button></div>
js:
methods: {
beforeUpload(file) {
//文件类型
const isType = file.type === 'application/vnd.ms-excel'
const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
const fileType = isType || isTypeComputer
if (!fileType) {
this.$message.error('上传文件只能是xls/xlsx格式!')
}
// 文件大小限制为10M
const fileLimit = file.size / 1024 / 1024 < 10
if (!fileLimit) {
this.$message.error('上传文件大小不超过10M!')
}
return fileType && fileLimit
},
// 自定义上传方法,param是默认参数,可以取得file文件信息,具体信息如下图
uploadHttpRequest(param) {
const formData = new FormData() //FormData对象,添加参数只能通过append('key', value)的形式添加
formData.append('file', param.file) //添加文件对象
formData.append('uploadType', this.is_type)//接口要传的参数
// 调用接口api
importData(formData).then((data) => {
if (data.code == 200) {
this.msgSuccess('成功')
param.onSuccess() // 上传成功的文件显示绿色的对勾
this.fileList = []
this.is_type = ''
} else {
this.msgError(data.msg)
}
})
},
// 点击上传:手动上传到服务器,此时会触发组件的http-request
submitUpload() {
this.$refs.upload.submit()
},
// 文件发生改变
fileChange(file, fileList) {
if (fileList.length > 0) {
this.fileList = [fileList[fileList.length - 1]] // 展示最后一次选择的文件
}
},
// 移除选择的文件
fileRemove(file, fileList) {
if (fileList.length < 1) {
this.uploadDisabled = true //未选择文件则禁用上传按钮
}
},
// 取消
closeDialog() {
this.$refs.upload.clearFiles() //清除上传文件对象
this.fileList = [] //清空选择的文件列表
this.$emit('close', false)
},
},
图片
页面:
html:
js: