Vue project gets upload and download progress

in daily projects 

It takes a long time to download or upload large files without any prompt, and the user experience is poor.

Needs to be optimized, prompts that the file is being downloaded, and displays the progress percentage.

 1.onUploadProgress file upload progress monitoring

Generally  onUploadProgress is used to monitor the progress of file upload, and onUploadProgress is an event in axois, so we can use it in the encapsulated axois request as follows

//封装好的 axois
import request from '@/utils/request';

export function upload(...,onUploadProgress){
    return request({
    ...,
    //此处使用 上传监听
    onUploadProgress
    })
}
//使用

upload(...,uploadProgress );

 const uploadProgress = (ps) => {
      progressTitle.value = `进度:${Math.floor(
        (ps.loaded / ps.total) * 100,
      )}%`;
  };

 2.onDownloadProgress file download progress monitoring

The usage is similar to the monitoring of file upload progress, but this method is used to monitor the progress of downloading, and is used for streaming (Blob) downloading

//封装好的 axois
import request from '@/utils/request';

export function download(...,onUploadProgress){
    return request({
    ...,
    //此处使用 上传监听
    onUploadProgress
    })
}
//使用

download(...,onDownloadProgress );

 const onDownloadProgress = (ps) => {
      progressTitle.value = `进度:${Math.floor(
        (ps.loaded / ps.total) * 100,
      )}%`;
  };

First of all, we can know from axois that the progress of file upload and download is obtained from onUploadProgress (obtaining file upload progress event) and onDownloadProgress (file download progress event) in axois. In the vue project, we generally package axois twice

 Take uploading as an example: the code that generally encapsulates the call is as follows

 

The progress is obtained as follows:

 

 The main code to get the progress

(ps) => {
      progressTitle.value = `进度:${Math.floor((ps.loaded / ps.total) * 100)}%`;
    }

Guess you like

Origin blog.csdn.net/weixin_49014702/article/details/127754164