自定义element UI el-upload组件多文件上传列表显示及进度条问题

本文档介绍如何在Vue中使用el-upload组件结合axios进行多文件上传,并在上传过程中显示进度条。当使用http-request覆盖默认上传行为以进行Base64转换时,详细展示了如何维护上传状态和进度条显示。通过自定义beforeUpload和onUploadProgress事件,实现了文件上传的进度跟踪和状态更新。同时,给出了详细的代码实现,包括UI布局、逻辑处理和Base64转码函数。

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

使用el-upload组件上传没有其他要求时进度条显示是没有问题的,但是要对上传的数据进行特殊处理时(如转成base64等),就需要用自定义上传用http-request方法,这时进度条就不显示了或者显示有问题,查了很多资料大多数是针对单文件上传的,多文件上传几乎没有,于是自己决定实现一个

 一、 ui

 <el-upload
        ref="uploadMutiple"
        action=""
        :show-file-list="false"
        :multiple="true"
        :before-upload="beforeUpload"
      >
        <el-button size="small" type="primary">选择文件上传</el-button>
      </el-upload>
      <el-table :data="uploadFilesList" style="width: 100%">
        <el-table-column prop="name" :show-overflow-tooltip="true" label="名称">
          <template slot-scope="scope">
            <i style="color:#409EFF" class=" el-icon-s-order" />{{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="是否成功" width="300">
          <template slot-scope="scope">
            <template v-if="scope.row.status==='success'">上传成功!</template>
            <template v-else-if="scope.row.status==='error'">上传失败!</template>
            <el-progress v-else :percentage="scope.row.progress" />
          </template>
        </el-table-column>
        <el-table-column width="120" prop="size" label="大小" />
        <el-table-column prop="name" width="180" :show-overflow-tooltip="true" label="功能">
          <template>
            <el-button type="primary" size="mini">删除</el-button>
            <el-button type="primary" size="mini">下载</el-button>
          </template>
        </el-table-column>
      </el-table>

二 、逻辑

 

 methods: {
    beforeUpload(file) {
      const fileList = {}
      for (const key in file) {
        fileList[key] = file[key]
      }
      // status:uploading、success、error 文件上传状态
      // progress 文件上传进度
      this.uploadFilesList.push({ ...fileList, progress: 0, status: 'uploading' })
      this.httpRequest(file, parms => {
        this.showProgress(fileList, parms)
      })
      // 阻止 el-upload的默认上传
      return false
    },
    showProgress(file, parms) {
      const { progress, status } = parms
      const arr = [...this.uploadFilesList].map(items => {
        if (items.uid === file.uid) {
          items.progress = progress
          items.status = status
        }
        return items
      })
      this.uploadFilesList = [...arr]
    },
 async httpRequest(file, callback) {
      const resBase64 = await getBase64(file)// Base64转码
      const params = { base64: resBase64.split(',')[1] }// 组合适合自己的参数
      let progress = 0
      axios({
        headers: { 'Content-Type': 'application/json;charset=UTF-8' },
        method: 'post',
        url: '******************',
        data: params,
        onUploadProgress: progressEvent => { // 获取文件上传进度 axios自带的
          progress = (progressEvent.loaded / progressEvent.total * 100) | 0
          callback({ progress, status: 'uploading' })
        }
      }).then(() => { // 成功状态
        callback({ progress, status: 'success' })
      }).catch(() => { // 失败状态
        callback({ progress, status: 'error' })
      })
    }
}

三、base64转码

const getBase64 = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    let fileResult = ''
    reader.readAsDataURL(file)
    // 开始转
    reader.onload = () => { fileResult = reader.result }
    // 转 失败
    reader.onerror = error => { reject(error) }
    // 转 结束  咱就 resolve 出去
    reader.onloadend = () => { resolve(fileResult) }
  })
}

Vue3中结合Element UI (el-upload) 实现文件上传显示进度条,你可以按照以下步骤操作: 1. 首先,在项目中安装Element UI以及Vue CLI(如果还没有安装): ```bash npm install element-ui@latest vue@next ``` 2. 引入必要的组件和样式: ```javascript import { ElUpload } from 'element-plus'; import '@element-plus/lib/theme-chalk/index.css'; ``` 3. 创建一个组件,例如`FileUploader.vue`,然后在模板里使用`ElUpload`组件: ```html <template> <div> <el-upload :action="uploadUrl" :on-progress="handleProgress" :before-upload="beforeUpload" :file-list="files" ref="upload" > <el-button slot="trigger">选择文件</el-button> <p class="tip" v-if="fileList.length > 0"> 已上传{{ fileList.length }}个文件 </p> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div> </el-upload> </div> </template> <script setup> const uploadUrl = '/api/upload'; // 你的实际上传接口地址 const files = ref([]); const handleProgress = (percentage, file) => { console.log(`上传进度 ${percentage}%`); }; const beforeUpload = async(file) => { if (!file.type.match('image/jpeg|image/png')) { message.error('只支持jpg和png格式'); return false; } return true; // 如果验证通过,返回true允许上传 }; </script> ``` 这里我们设置了`handleProgress`函数来处理上传过程中的百分比更新,`beforeUpload`函数用于文件类型检查和预处理。 4. 现在你可以在其他地方引用这个`FileUploader`组件在父组件中监听上传结果等事件,以便进一步处理。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值