此下载功能针对文件是url,例如http://xxxx/图片.jpg, http://xxx/视频.mp4, http://xxx/应用.apk等等,可以监听进度 ,失败等等。
function downFile (url, name){
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob'; // 返回类型blob
// 监听进度
xhr.onprogress = function (e) {
if (e.lengthComputable) {
// 文件总体积
console.log(e.total);
// 已下载体积
console.log(e.loaded);
}
}
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let blob = this.response;
// 转换一个blob链接
let u = window.URL.createObjectURL(new Blob([blob]));
let a = document.createElement('a');
a.download = name;
a.href = u;
a.style.display = 'none'
document.body.appendChild(a);
a.click();
a.remove();
// 释放
window.URL.revokeObjectURL(u);
}
};
xhr.onerror = function(){
console.log('失败');
}
xhr.send();
}