使用http-request自定义上传,触发on-success,on-error钩子。
template
<el-row>
<el-col :span="20">
<el-input v-model="file" placeholder="请上传文件" disabled />
</el-col>
<el-col :span="4">
<el-upload
:http-request="handleHttprequest"
:multiple="false"
:show-file-list="false"
:auto-upload="true"
action=""
:on-success="(res) => file = res"
:on-error="() => file = ''"
>
<el-button icon="el-icon-upload2" type="primary">上传文件</el-button>
</el-upload>
</el-col>
</el-row>
js
import request from '@/utils/request'
handleHttprequest(params) {
const formData = new FormData()
formData.append('file', params.file)
// axios的二次封装
request({
url: '/api/upload',
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
data: formData
}).then((res) => {
this.$message({ type: 'success', message: '上传成功' })
params.onSuccess(res)
}).catch(() => {
this.$message({ type: 'error', message: '上传失败' })
params.onError()
})
}
也可以返回Promise,on-success,on-error钩子就会被执行。
handleHttprequest(params) {
return new Promise((resolve, reject) => {
省略同上......
request({省略同上.....}).then((res) => {
this.$message({ type: 'success', message: '上传成功' })
resolve(res)
}).catch(() => {
this.$message({ type: 'error', message: '上传失败' })
reject()
})
})
}