BOYYANG/1/blog/compressed/蓝发漂亮女孩 侧脸 4k动漫壁纸3840x2160_彼岸图网-59d4532e9bfd8d998238a742898f857c

使用XMLHttpRequest 下载图片并且监听下载进度

作者: boyyang
分类: 前端开发
发布: 2025-03-13 10:28:01
更新: 2025-03-21 06:06:09
浏览: 126

       下载文件直接打开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,
}


#vue3
#前端
#图片下载
#javascript
#typescript