原文教程:
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) })();