发布时间:2023-01-28 文章分类:编程知识 投稿人:李佳 字号: 默认 | | 超大 打印

参考:https://www.cnblogs.com/lxlx1798/articles/16969244.html

要么使用流读取器,要么使用 Reponse 的方法来获取结果,不能同时使用两种方法来读取相同的响应。

直接获取:

Response.blob() 方法返回一个 resolve 返回值为 Blob 对象的 Promise

fetch(videoUrl).then(res => {
                const p = res.blob()
                return res.blob()
            }).then(blob => {
                const a = document.createElement("a");
                a.style.display = 'none'
                document.body.append(a)
                const url = window.URL.createObjectURL(blob)
                a.href = url
                a.download = item.name
                a.click()
                document.body.removeChild(a)
                window.URL.revokeObjectURL(url)
            })

流读取:

Response.body 是一个 ReadableStream 对象

ReadableStream.getReader() 创建流读取器,并且会把流锁定,默认返回的是ReadableStreamDefaultReader 类型

ThegetReader()method of theReadableStreaminterface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.

response.headers.get('Content-Length') 得到响应的总长度

ReadableStreamDefaultReader.read() 方法得到一个 Promise 对象,可以获取到流内部序列中的下一个分块,循环调用直到完成,同时收集数据得到一个Uint8Array 数组

最后转换成 Blob 就可以完成下载了

const videoUrl = 'video url'
const response = await fetch(videoUrl) const reader = response.body.getReader() const contentLength = +response.headers.get('Content-Length') let receivedLength = 0 let chunks = [] while (true) { const { done, value } = await reader.read(); if (done) { break } chunks.push(value) receivedLength += value.length // 下载进度 console.log(`Reveived ${receivedLength} of ${contentLength}`) } const a = document.createElement("a"); a.style.display = 'none' document.body.append(a) const url = window.URL.createObjectURL(new Blob(chunks, { type: 'video/mp4'} )) a.href = url a.download = item.name a.click() document.body.removeChild(a) window.URL.revokeObjectURL(url)

用到的一些方法:

fetch()

The globalfetch()method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available.

The promise resolves to theResponseobject representing the response to your request.

Afetch()promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). Afetch()promisedoes notreject on HTTP errors (404, etc.). Instead, athen()handler must check theResponse.okand/orResponse.statusproperties.

WindowOrWorkerGlobalScopeis implemented by bothWindowandWorkerGlobalScope, which means that thefetch()method is available in pretty much any context in which you might want to fetch resources.

Thefetch()method is controlled by theconnect-srcdirective ofContent Security Policyrather than the directive of the resources it's retrieving.

ReadableStream.getReader()

ThegetReader()method of theReadableStreaminterface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.

ReadableStreamDefaultReader.read()

Theread()method of theReadableStreamDefaultReaderinterface returns aPromiseproviding access to the next chunk in the stream's internal queue.

URL.createObjectURL()

TheURL.createObjectURL()static method creates a string containing a URL representing the object given in the parameter.

The URL lifetime is tied to thedocumentin the window on which it was created. The new object URL represents the specifiedFileobject orBlobobject.

To release an object URL, callrevokeObjectURL().

URL.revokeObjectURL()

TheURL.revokeObjectURL()static method releases an existing object URL which was previously created by callingURL.createObjectURL().

Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer.