本文已参与「新人创作礼」活动,一起开启掘金创作之路。
本文已参与「新人创作礼」活动,一起开启掘金创作之路。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style></style>
<style>
</style>
</head>
<body>
<script>
/**
* 将url文件下载到本地
* @param fileUrl {String} 文件链接
* @param fileName {String} 文件名字
* @return void
*/
downloadFile("http://123.234.218.58:65001/zhsw/mainframe/myModules/video/video.mp4",'aa')
async function downloadFile(fileUrl,fileName) {
let blob = await getBlob(fileUrl);
saveFile(blob, fileName);
}
function getBlob(fileUrl) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open('GET', fileUrl, true);
//监听进度事件
xhr.addEventListener(
'progress',
function (evt) {
if (evt.lengthComputable) {
let percentComplete = evt.loaded / evt.total;
// percentage是当前下载进度,可根据自己的需求自行处理
let percentage = percentComplete * 100;
console.log(percentage)
}
},
false
);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
}
function saveFile(blob, fileName) {
// ie的下载
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
// 非ie的下载
const link = document.createElement('a');
const body = document.querySelector('body');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
// fix Firefox
link.style.display = 'none';
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
}
</script>
</body>
</html>