前 言:vue使用element UI项目中经常有文件上传、批量导入等需求,那我们自然会使用Upload组件,其Attribute提供的on-success、on-error等钩子基本能完成大部分需求,有额外需求的则可以使用http-request自定义上传去覆盖默认上传行为。
Let's 一起 see see~
常用参数:
说明 | 备注 | |
---|---|---|
action | 上传的地址 | 必填!常填写后台接口 |
before-upload | 上传文件前的钩子 | 参数为上传的文件,特点是若返回 false 或者返回 Promise 且被 reject,则停止上传。那我们就常用于限制传入格式和大小 |
on-success | 上传成功时的钩子 | 该钩子返回的是一个函数,常用第一个参数response来做上传成功后的效果处理 |
on-error | 上传失败时的钩子 | 已经上传失败了,常用于提升用户使用效果,给用户一些提示,记得要使用clearFiles方法清除已上传的文件列表 |
http-request | 自定义上传的实现 | 覆盖默认的上传行为! 1:覆盖了action地址(action必填,空也可以) 2:默认的on-success、on-error、on-progress等钩子都失效了 |
默认行为:
<template>
<el-upload
ref="uploadFile"
:action="'/xiangMuWenJian/testJieKou'"
:before-upload="handleBeforeUpload"
:on-success="fileUpSuccess"
:on-error="fileUpError"
multiple >
<el-button>批量导入</el-button>
</el-upload>
</template>
<script>
export default{
methods:{
// 上传前
handleBeforeUpload (file) {
const isXls = file.name.replace(/.+\./, "") === 'xls'
if (!isXls) {
this.$message.error('导入文件只能是 xls 格式!')
return false
}
// 根据需求添加加载框(此处我举例了全局加载框)
Loading.service({ lock: true, text: '正在导入数据中,请耐心等待', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.4)', })
},
// 上传成功
fileUpSuccess (response) {
this.$refs.uploadFile.clearFiles()
// 此处清除加载框
// 可以根据response参数获取接口返回的一些信息进行后续操作
if (response.code == 200) {
this.$message.success({ message: "导入成功" + response.bean.sucessNum + '条' })
this.submitQuery() // 列表页使用的话记得刷新数据
} else this.$message.error({message: response.msg})
},
// 上传失败
fileUpError () {
// 此处清除加载框
this.$refs.uploadFile.clearFiles()
this.$message.warning({
message: '上传失败,请稍后再试!'
})
}
}
}
</script>
自定义行为:
使用场景:一般我们项目中的接口timeout都是统一配置,给一个默认值。那对于使用Upload上传数量大时可能就需要拉长timeout,那我们用action配置接口的时候不好改timeout,这个时候怎么处理呢??唉嗨,咱可以用自定义上传解决,那就上代码!
<template>
<el-upload
ref="uploadFile"
:action=""
:before-upload="handleBeforeUpload"
:http-request="httpRequest"
multiple >
<el-button>批量导入</el-button>
</el-upload>
</template>
<script>
export default(){
methods:{
httpRequest (item) {
const fd = new FormData()
fd.append('file', item.file)
this.$refs.uploadFile.clearFiles()
const loadingInstance = Loading.service({ lock: true, text: '正在导入数据中,请耐心等待', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.4)', })
axios({
method: 'post',
url: '/xiangMuWenJian/testJieKou',
data: fd,
timeout: 1800000,
headers: {
'Content-Type': 'multipart/form-data'
},
}).then((res) => {
this.$nextTick(() => { loadingInstance.close() })
if (res.data.code == 200) {
this.$message.success({message: "导入成功" + res.data.bean.sucessNum + '条'})
this.submitQuery() // 列表页使用的话记得刷新数据
} else this.$message.error({message: res.data.msg})
}).catch(() => {
this.$nextTick(() => { loadingInstance.close() })
this.$refs.uploadFile.clearFiles()
this.$message.warning({message: '上传失败,请稍后再试!'})
})
}
}
}
</script>
:
咱就是说一旦使用了自定义方法,那默认方法就失效了,在上方代码中then就替代了on-success的效果,catch替代了on-error的效果,一般这些异常和成功处理就够用了。如果还需要其他的可以参考源码中的方法进行仿写。
以上,over!欢迎补充~