如果想知道下载一个文件需要多长时间,network是可以看到的,但是如何记录下来呢?
方法1:文件大小÷网速
网速获取:navigator.connection.downlink
因为缓存、IE不支持等因素影响,不够准确。
方法2:后端获取写文件流的时间
误差较大
方法3:XMLHttpRequest
// 服务端到客户端的传输进程(下载)
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total * 100;
// ...
} else {
// 总大小未知时不能计算进程信息
}
}
未尝试过,理论上可行
方法4:promise
const time1 = new Date().getTime();
this.axios.get(`xxx`).then(res => {
const content = res;
const blob = new Blob([content]);
const fileName = `文件名.xxx`;
const elink = document.createElement("a");
elink.download = fileName;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href);
document.body.removeChild(elink);
}).then(res => {
const time2 = new Date().getTime();
console.log('成功', time2 - time1);
}).catch(() => {
const time2 = new Date().getTime();
console.log('失败', time2 - time1);
})
亲测可行,与network显示的时间相差无几。
推荐方法4