This commit is contained in:
2024-06-28 21:31:48 +08:00
parent 48aced8b6e
commit 06a2ea704e
6 changed files with 175 additions and 34 deletions

View File

@@ -1,16 +1,44 @@
export const useDownload = (url: string, filename: string) => {
import { EventEmitter } from 'events'
export const useDownload = (url: string, filename: string): {
download: () => void
progressEmitter: EventEmitter
} => {
const progressEmitter = new EventEmitter()
const download = () => {
fetch(url)
.then((response) => response.blob())
.then((blob) => {
const url = window.URL.createObjectURL(new Blob([blob]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
link.parentNode?.removeChild(link)
})
const xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.onprogress = (event) => {
if (event.lengthComputable) {
const percentComplete = (event.loaded / event.total) * 100
progressEmitter.emit('progress', percentComplete)
}
}
xhr.onload = function () {
if (this.status === 200) {
const blob = new Blob([this.response], { type: 'application/octet-stream' })
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
link.parentNode?.removeChild(link)
progressEmitter.emit('done')
} else {
progressEmitter.emit('error', new Error('资源已过期或不存在'))
}
}
xhr.onerror = function () {
progressEmitter.emit('error', new Error('网络错误,下载失败'))
}
xhr.send()
}
return {
download,
progressEmitter,
}
return { download }
}