axios、fetch、ajax 请求下载文件时的进度条-下载进度-上传进度-请求进度
原文教程:
fetch 的实现:https://javascript.info/fetch-progress
备注
1、我的场景是请求 csv 文件,我希望获取下载进度。下面是各种实现的代码。
2、如果是上传进度可能不太一样。有必要的话将来回来补充。
3、如果是请求正常接口的话,似乎无法获得进度,是一步到位的。也就是: { loaded: 【文件总大小】,total: 0 }。所以无法用于请求普通接口。
axios 请求下载文件时的进度条事件
;(async () => { // 启动计时器 console.time('📝耗时统计:') // your code... await axios({ url: './全量数据-20220309144842.csv', method: 'get', onDownloadProgress(progress) { const step = Math.round(progress.loaded / progress.total * 100) console.log(step + '%') } }).then(res => { console.log('正在解析...') const data = csvJSON(res.data) console.log('解析完成', data) }) // 停止计时,输出时间 console.timeEnd('📝耗时统计:') })();
ajax 请求下载文件时进度条事件
var xhrOnProgress = function (fun) { return function () { var xhr = $.ajaxSettings.xhr() xhr.onprogress = fun return xhr } } $.ajax({ type: 'GET', url: './全量数据-20220309144842.csv', xhr: xhrOnProgress(function (progress) { const percent = Math.round(progress.loaded / progress.total * 100) console.log(percent + '%') }) })
fetch 请求下载文件时进度条事件
/* https://javascript.info/fetch-progress */ ;(async () => { // Step 1: start the fetch and obtain a reader let response = await fetch('./全量数据-20220309144842.csv'); const reader = response.body.getReader(); // Step 2: get total length const contentLength = +response.headers.get('Content-Length'); // Step 3: read the data let receivedLength = 0; // received that many bytes at the moment let chunks = []; // array of received binary chunks (comprises the body) while (true) { const { done, value } = await reader.read(); if (done) { break; } chunks.push(value); receivedLength += value.length; console.log(`Received ${receivedLength} of ${contentLength}`, ) const percent = Math.round(receivedLength / contentLength * 100) console.log(percent + '%') } // Step 4: concatenate chunks into single Uint8Array let chunksAll = new Uint8Array(receivedLength); // (4.1) let position = 0; for (let chunk of chunks) { chunksAll.set(chunk, position); // (4.2) position += chunk.length; } // Step 5: decode into a string let result = new TextDecoder("utf-8").decode(chunksAll); // We're done! console.log(20220309231613, result) })();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)