前言
本文所用页面组件是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;
})
}