我正在使用blob在ajax的javascript下载器中工作。我想知道是否可以在客户端网络从同一点断开后继续下载。
我做了一个按钮,当单击该按钮时,打开一个ajax并再次发送,但它重新开始下载。
var xhr = new XMLHttpRequest();
var x0 = 0, y0 = 0;
xhr.open('GET', 'download.rar');
xhr.responseType = 'blob';
xhr.onerror = function(e){
console.log(xhr.readyState);
div = document.createElement('div');
document.body.appendChild(div);
div.onclick = function(){
xhr.open('GET', 'download.rar');
xhr.responseType = 'blob';
xhr.send();
}
div.innerHTML = 'CLIQUE PARA CONTINUAR';
}
console.log(xhr);
function normalizeSize( size ){
if( size > Math.pow( 1024, 3) ){
return (parseInt(size)/Math.pow( 1024, 3)).toFixed(2)+' Gb';
}else if( size > Math.pow( 1024, 2) ){
return (parseInt(size)/Math.pow( 1024, 2)).toFixed(2)+' Mb';
}else if( size > 1024 ){
return (parseInt(size)/1024).toFixed(2)+' Kb';
}else{
return size.toFixed(2)+' bytes';
}
}
xhr.onprogress = function(e){
console.log(e);
var d = new Date();
var time = d.getTime();
if( x0 != 0 && y0 != 0 ){
let spd = 1000*(e.loaded - x0)/(parseInt(e.timeStamp - y0));
let medida = '';
if( spd > 1024*1024 ){
spd2 = spd/(1024*1024);
medida = 'mb/s';
}else if( spd > 1024 ){
spd2 = spd/1024;
medida = 'kb/s';
}else{
spd2 = spd;
medida = 'bytes/s';
}
spd2 = Math.round(spd2);
document.getElementById('velocidade').innerHTML = 'Velocidade: '+spd2+medida;
document.getElementById('tempo_falta').innerHTML = 'Falta: '+(e.total-e.loaded)/spd+' segundos';
}
document.getElementById('progress').value = (e.loaded/e.total)*100;
document.getElementById('tempo_gasto').innerHTML = 'Tempo Gasto: '+Number.parseFloat(e.timeStamp/1000).toFixed(2)+' segundos';
document.getElementById('valor_baixado').innerHTML = 'Baixado: '+normalizeSize(e.loaded);
document.getElementById('valor_falta').innerHTML = 'Falta: '+normalizeSize(e.total - e.loaded);
document.getElementById('valor_total').innerHTML = 'Tamanho do arquivo: '+normalizeSize(e.total);
x0 = e.loaded;
y0 = e.timeStamp;
}
xhr.onload = function(e){
document.getElementById('msgs').innerHTML = 'decodificando...';
let blob = xhr.response;
let url = URL.createObjectURL(blob);
let a = document.createElement('a');
a.download = 'download.rar';
a.href = url;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.getElementById('msgs').innerHTML = 'baixando';
}
xhr.send();
我希望出现错误后,下载会继续并且不会重新启动。