js如何分片下载超出2G的大文件?

请问js如何分片下载超出2G的大文件?

我使用了分片下载的代码,文件不大的时候,可以正常下载。当文件太大的时候,文件要么不对,要么就是把浏览器搞崩了

const blob = new Blob(this.splitFileList, { type: this.mineType })
saveAs(blob, this.fileName)

saveAs函数是file-save库里的,this.splitFile是返回的blob文件流数组对象,我这里是每拿到一个blob文件流,就push到这个数组里

分片下载 可以限制大小啊,你咋搞的

具体解释可以参考这篇文章:https://blog.csdn.net/weixin_43576565/article/details/131334460
可以使用Fetch API来下载文件,同时使用了Range头来告诉服务器只需要下载文件的一部分。我们将文件大小分割为块,每次下载一块数据,最后将数据组合成一个Blob对象进行下载。


async downloadFile(url, fileName) {
    const CHUNK_SIZE = 1024 * 1024 * 10 // 每次下载10MB
    const response = await fetch(url)
    const contentRange = response.headers.get('content-range') 
    const fileSize = contentRange ? Number(contentRange.split('/')[1]) : response.headers.get('content-length')
    const fileStream = []
    let offset = 0

    while (offset < fileSize) {
        const end = Math.min(offset + CHUNK_SIZE, fileSize)
        const options = {
            headers: { 'Range': `bytes=${offset}-${end - 1}` }
        }
        const blob = await fetch(url, options).then(res => res.blob())
        fileStream.push(blob)
        offset = end
    }

    const blob = new Blob(fileStream, { type: response.headers.get('content-type') })
    saveAs(blob, fileName)
}