使用XMLHttpRequest 下载图片并且监听下载进度
 Sonder
2025-03-25
1777字 
4分钟 
 浏览 (521) 
下载文件直接打开a标签进行下载无法监听实时精度。使用XMLHttpRequest 的progress事件监听获取当前下载数据。
const useDownload = () => {
   const loading = ref<boolean>(false)
   const percent = ref<number>(0)
   const imageDownloadByBlob = (url: string, name: string) => {
       loading.value = true
       return new Promise((resolve) => {
           const x = new XMLHttpRequest()
           x.open('get', url, true)
           x.responseType = 'blob'
           x.addEventListener('progress', (evt) => {
               if (evt.lengthComputable) {
                   percent.value = Number(((evt.loaded / evt.total) * 100).toFixed(0))
               }
           }, false)
           x.onload = () => {
               if (x.status === 200) {
                   saveFile(x.response, name)
                   const t = setTimeout(() => {
                       percent.value = 0
                       loading.value = false
                       clearTimeout(t)
                   }, 1000)
                   resolve(true)
               }
           }
           x.send()
       })
   }
   const saveFile = (blob: Blob, filename: string) => {
       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)
   }
   return {
       loading,
       percent,
       imageDownloadByBlob,
   }
}
export {
   useDownload,
}