使用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文章来源:https://www.toymoban.com/news/detail-732663.html
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钩子就会被执行。文章来源地址https://www.toymoban.com/news/detail-732663.html
handleHttprequest(params) {
return new Promise((resolve, reject) => {
省略同上......
request({省略同上.....}).then((res) => {
this.$message({ type: 'success', message: '上传成功' })
resolve(res)
}).catch(() => {
this.$message({ type: 'error', message: '上传失败' })
reject()
})
})
}
到了这里,关于el-upload自定义上传http-request的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!