el-upload自定义上传http-request

使用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()
	   })
	 })
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 el-upload 组件来自定义上传http-requestel-uploadElement UI 框架中用于文件上传的组件,支持多种自定义配置选项。 要实现自定义上传http-request,您可以通过设置 el-upload 组件的 action 属性来指定上传文件的接口地址。例如: ```html <el-upload action="/your-upload-api" :http-request="uploadRequest" > <!-- 填充上传组件的内容 --> </el-upload> ``` 然后,在 Vue 实例的 methods 中定义 uploadRequest 方法来处理上传请求。uploadRequest 方法会接收一个参数,其中包含了上传文件的相关信息,如文件对象、文件名等。您可以在该方法中使用 axios 或其他网络请求库发送自定义上传请求。例如: ```js methods: { uploadRequest(file) { // 构建 FormData 对象,将文件和其他参数添加到 FormData 中 const formData = new FormData(); formData.append('file', file.raw); formData.append('name', file.name); // 使用 axios 发送自定义上传请求 axios.post('/your-upload-api', formData) .then(response => { // 处理上传成功的响应 console.log(response.data); }) .catch(error => { // 处理上传失败的错误 console.error(error); }); } } ``` 在 uploadRequest 方法中,您可以根据实际需求构建 FormData 对象,并发送自定义上传请求。在请求成功或失败时,您可以进行相应的处理逻辑。 这样,您就可以使用 el-upload 组件来实现自定义上传http-request。希望对您有所帮助!如有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值