js 通过url 转blob下载文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button onclick="xhrequest()">下载</button>
<script>
let downloadBlob = (blob, fileName) => {
try {
const href = window.URL.createObjectURL(blob);
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob, fileName);
} else {
const downloadElement = document.createElement("a");
downloadElement.href = href;
downloadElement.target = "_blank";
downloadElement.download = fileName;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
}
} catch (e) {
console.log("下载失败");
}
};
async function xhrequest(callback) {
let url =
"https://1252524126.vod2.myqcloud.com/2919df88vodtranscq1252524126/edee603b3701925925677178599/v.f1010.mp3";
let data = await fetch(url)
.then((response) => response.blob())
.then((res) => {
console.log(res);
let blod = new Blob([res]);
let name = "1.mp3";
downloadBlob(blod, name);
});
return data;
}
</script>
</body>
</html>