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) })();