Get downloading progress from `requestUrl()`

I want let the downloading progress visible to the users, as they may be faced with weak network. Knowing the downloading progress is slow can help them abort this time. Can I do this with existing APIs?

I did searched for one directly using fetch() API, however I came across some difficulties requesting to github release pages.

Sample code lines here. This can be directly copy-pasted to browser console and take effect.

function progress(percentage) {
	console.log(percentage + '%');
}

async function download_with_progress() {
	console.log('downloading with fetch()...');
	const response = await fetch(
		'https://fetch-progress.anthum.com/30kbps/images/sunrise-baseline.jpg'
	);
        
	const contentLength = response.headers.get('content-length');
	const total = parseInt(contentLength, 10);
	let loaded = 0;
	const res = new Response(
		new ReadableStream({
			async start(controller) {
				const reader = response.body?.getReader();
				if (reader)
					for (;;) {
						const { done, value } = await reader.read();
						if (done) break;
						loaded += value.byteLength;
						progress(Math.round((loaded / total) * 100));
						controller.enqueue(value);
					}
				controller.close();
			},
		})
	);
	const blob = await res.blob();
	console.log('download completed');
}

download_with_progress()

Credits to javascript - Fetch API Download Progress Indicator? - Stack Overflow

use fetch directly?

Yeah I’m working on this but can’t get binary file from github release, instead what I downloaded is actually the release json. So weird. Will post back if I got the solution.

Have you set the accept-type?

Yes I included this, but got json. Not knowing what happened.

Sending the same request using requestUrl() api works just fine.