el-upload自定义上传http-request

该文章展示了在Vue.js中如何使用http-request属性来自定义文件上传过程,通过触发on-success和on-error钩子来处理上传结果。利用axios进行HTTP请求,并在上传成功或失败时显示消息。同时,可以返回Promise来同步这些钩子的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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()
	   })
	 })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值