vue文件上传,文件打不开。文件上传 on-progress不触发

该代码示例展示了如何在Vue.js应用中使用ElementUI的el-upload组件实现文件上传并显示进度条。关键在于通过http-request属性覆盖默认的上传行为,监听on-progress事件更新进度,并使用axios发送POST请求,处理上传进度和成功后的响应。
摘要由CSDN通过智能技术生成

在这里插入图片描述

//文件上传带进度条
   <el-upload
          v-model:file-list="fileList"
          :limit="3"
          :on-progress="beforeAvatarUpload"
          //on-progress 不触发,触发的关键在于覆盖原有的http请求
          :http-request="getFile"
          :action="`${app.api}/student/student/import`"
        >
          <span v-if="jinDu">
            <el-progress style="width: 245px; height: 19px" :text-inside="true" :stroke-width="20"
                         :percentage="percentage"/>
          </span>
          <span v-if="isUpload" style="color: #59c2c7;cursor:pointer;"
                @click="uploadChangeValue">导入学生学籍信息</span>
          <template #tip>
            <span style="color: #ff8282; margin-left: 20px">{{ importText }}</span>
          </template>
        </el-upload>


<script setup lang="ts">
let percentage = ref(0);
const beforeAvatarUpload = (event: any) => {
  debugger
  let loadProgress = Math.floor(event.percent); //这就是当前上传的进度
  //可以进行其他逻辑
  percentage.value = loadProgress;
  importText.value = "学籍信息导入中……";
  if (percentage.value == 100) {
    importText.value = "学籍导入成功!"
  }
};

const getFile = (val:any) => {
  const formData = new FormData();
  formData.append('file', val.file)
  axios({
    method: 'post',
    data:formData,
    url: `${app.api}/student/student/import`,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      "token":token
    },
    onUploadProgress: (progressEvent) => {
      let num = progressEvent.loaded / progressEvent.total * 100 | 0;
      val.onProgress({percent: num})
    },
    //此处由于后端返回的是一个流的形式,所以请求必须带 responseType: 'blob',意思是后端返回的是一个流的形式,如果不带,那么后端返回的流,你下载的文件就会无法打开
    responseType: 'blob'
  }).then((res:any) => {
    if (res.code){

    }else {
      downloadUrl.value = window.URL.createObjectURL(new Blob([res.data]))
    }
  })
}

</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值