Fetch封装:文件下载进度

javascript
const downloadProgress = 0 // 下载进度

// Step 1:启动 fetch,并获得一个 reader
let response = await fetch(
    URL,
    {
        headers: {
            Authorization: Token
        }
    }
)
const reader = response.body.getReader()

// Step 2:获得总长度(length)
const contentLength = +response.headers.get('Content-Length')

// Step 3:读取数据
let receivedLength = 0 //当前接收到了这么多字节
let chunks = [] //接收到的二进制块的数组(包括 body)
while (true) {
    const { done, value } = await reader.read()

    if (done) {
        break
    }

    chunks.push(value)
    receivedLength += value.length
    downloadProgress = Math.round((receivedLength * 100) / contentLength)
}

// Step 4:将块连接到单个 Uint8Array
let chunksAll = new Uint8Array(receivedLength) // (4.1)
let position = 0
for (let chunk of chunks) {
    chunksAll.set(chunk, position) // (4.2)
    position += chunk.length
}

const blob = new Blob([chunksAll])

let a = document.createElement('a')
document.body.appendChild(a) //兼容火狐,将a标签添加到body当中
let url = window.URL.createObjectURL(blob) // 获取 blob 本地文件连接 (blob 为纯二进制对象,不能够直接保存到磁盘上)
a.href = url
a.download = props.data.tencentFlag ? props.data.name + '.mp4' : props.data.name
a.target = '_blank' // a标签增加target属性
a.click()
a.remove() //移除a标签
window.URL.revokeObjectURL(url)