vue3+ts计算文件上传和下载进度条

前言

本文所用页面组件是antd3,通信采用axions库。

一、页面组件

上传:

<div class="isShowProgress" v-if="showProgress">
  <a-progress :percent="percentage" v-if="percentage!==0" :status="status" />
</div>

下载:

<div v-if="showUpProgress" >
 <a-progress type="circle" v-if="record.downloadStatus" :show-info="false" :percent="percentdown" :width="25" status="status" /
</div>

进度条的关键就是计算percent百分比。

二、axions异步函数

上传与下载:

//上传文件到S3
export async function s3upFiles(params:any,onUploadProgress:any ) {
    return http.request({
        url: `/api/api-gis/v1/s3/s3UploadFile`,
        method: "POST",
        //timeout:20*1000,
        data:params,
        onUploadProgress: onUploadProgress
    })
}
//下载文件,先从本地找,然后去S3找
export async function S3downLoadFile(id:number,onDownloadProgress:any) {
    return http.request({
        responseType: 'blob',
        url: `/api/api-gis/v1/s3/download/${id}`,
        method: 'GET',
        onDownloadProgress:onDownloadProgress  
    })
}

主要利用axions内置的 onUploadProgress和 onDownloadProgress函数来获取已上传或下载的文件大小。

三、进度条计算

上传:

    s3upFiles(formData, (progressEvent: any) => {
        showProgress.value = true;
        if (progressEvent.lengthComputable) {
          percentage = Number(
            ((progressEvent.loaded / progressEvent.total) * 99).toFixed(2))
        if (totalSize.value == loadedSize.value) {
        percentage.value == 100
        status.value = 'success'
      }else {
          status.value = 'exception'
        }
      }).then((res) => {
      }).catch((err) => {
      // 调用实例的失败方法通知组件该文件上传失败
      e.onError(err);
    });

下载:

//下载
const download = (record: any) => {
  record.downloadStatus = true;
  S3downLoadFile(record.id,(proevent:any)=>{
    showUpProgress.value=true;
    percentdown.value=Number((proevent.loaded/proevent.total)*100).toFixed(2)
    if(percentdown.value==100){
      showUpProgress.value=false;
      status.value = 'success'
    }
  }).then((res) => {
   //下载文件的格式
    let format = 'text/plain';
    switch (record.format) {
      case 1:
        format = 'image/tiff';
        break;
      case 2:
        format = 'application/zip';
        break;
      case 3:
        format = 'text/plain';
        break;
      case 4:
        format = 'application/zip';
        break;
    }
    //文件下载
    let blob = new Blob([res], { type: format });
    const link = document.createElement('a');
    let objectUrl = URL.createObjectURL(blob);
    link.href = objectUrl;
    link.download = record.name == null ? '地图数据' : record.code + "-" + record.name;
    link.click();
    URL.revokeObjectURL(objectUrl);
    //数据列表加载
    loadData();
    record.downloadStatus = false;
  })
}

Vue3中使用TypeScript进行多文件上传,你可以按照以下步骤进行操作: 1. 首先,创建一个文件上传组件。你可以使用`custom-upload`组件,并通过`v-model`绑定一个表单项,用于存储上传的文件列表。在`<script>`标签中,引入需要的接口类型和API封装方法。 ```javascript <template> <custom-upload v-model="formInline.attachmentResultList" :attr="attrResult" /> </template> <script> import { ref } from 'vue'; // 引入Vue3的ref方法 import { uploadFile } from '@/api'; export default { setup() { const formInline = ref({ attachmentResultList: [] }); const attrResult = ref({ id: 'fileUploadId', name: 'attachmentName', limit: 999, readonly: true }); return { formInline, attrResult }; } }; </script> ``` 2. 在API文件中,定义多文件上传的方法`uploadFile`。该方法接收一个`FormData`类型的参数,用于包含上传的文件数据。通过调用`http.upload`方法,并指定上传文件的URL路径和请求头,实现文件上传功能。 ```javascript // api.ts import http from '@/api'; import { UPLOAD_FILE } from '@/api/config/servicePort'; export const uploadFile = (params: FormData) => { return http.upload<Upload.ResFileList>(UPLOAD_FILE + '/file/uploadFile', params, { headers: { 'Content-Type': 'multipart/form-data' } }); }; ``` 3. 定义文件上传的接口类型。根据你的需求,可以根据接口返回的数据定义相应的类型。 ```javascript // interface.ts export namespace Upload { export interface ResFileList { id: string; fileName: string; fileUrl: string; uploadTime: string; operator: string; fileType: string; fileSize: number; fileOldname: string; } } ``` 通过上述步骤,你就可以在Vue3中使用TypeScript实现多文件上传的功能了。在你的组件中,用户可以选择多个文件进行上传,并且上传成功后,文件相关的信息将会被保存在`formInline.attachmentResultList`中,你可以根据业务需求进行进一步处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

定位算法工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值