import { ElMessage } from 'element-plus'
import { unLoading } from '@/utils/unLoading'
import { ref } from 'vue'
export async function download(url, fileName) {
const rate = ref(0)
const loading = unLoading(rate)
const blob = await fetch(url).then(async (res) => {
const reader = res.body.getReader()
const contentLength = +res.headers.get('Content-Length');
let receivedLength = 0;
let chunks = [];
while(true) {
const {done, value} = await reader.read();
if (done) {
break;
}
chunks.push(value);
receivedLength += value.length;
rate.value = Math.floor(receivedLength/contentLength * 100) + '%'
}
return new Blob(chunks, {type: 'application/octet-stream'});
});
loading.close()
ElMessage.success('下载成功')
const blobUrl = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.style.display = "none";
link.target = "_blank";
link.href = blobUrl;
const ext = url.split('.').pop();
link.download = `${fileName}.${ext}`;
document.body.appendChild(link);
link.click();
}