fetch实现带进度条可暂停断点续传文件下载效果代码
代码语言:html
所属分类:其他
代码描述:fetch实现带进度条可暂停断点续传文件下载效果代码,可以将浏览器带宽设为slow 3g并关闭缓存。
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <h1> Fetch可中断断点续传示例代码</h1> <div> <progress id="progress" max="1" value="0"></progress> <button id="action">开始下载</button> <span id="status"></span> </div> <p>可以将浏览器的带宽设为1g或2g,然后清空缓存查看效果</p> <p>如何下载的url<code>content-type: gzip</code>)可能会出错.</p> <img width="640" height="360" alt="" id="img" style="display: none"> <script> // WARNING: DO NOT USE THE CODE IN PRODUCTION, AS IT DOESN'T COVER ALL THE REQUEST AND ERROR CASES class ResumableFetch { constructor(input, init) { this.aborter = null; this.request = null; this.length = 0; this.total = null; this.done = false; this.contentType = null; this.chunks = []; // ignore called as `fetch(input: Request)` at this time this.input = input; this.init = init || {}; } start() { if (this.done) { return Promise.reject(new Error('The chunks have been piped out')); } if (this.aborter && !this.aborter.signal.aborted) { return this.request; } this.aborter = new AbortController(); const { headers = {} } = this.init; const init = { ...this.init, headers: { ...headers, ...(this.length ? { Range: `bytes=${this.length}-` } : false) }, signal: this.aborter.signal }; this.request = fetch(this.input, init).then(res => { this.contentType = res.headers.get('content-type'); const total = res.headers.get('content-length'); if (!this.length) { this.total = total; } else if (total === this.total) { // server may not support range request this.reset(); } return res.body.getReader(); }).then(reader => this.readChunks(reader)).then(chunks => { const stream = new ReadableStream({ start(controller) { const push = () => { const chunk = chunks.shift(); if (!chunk) { controller.close(); return; } controller.enqueue(chunk); push(); }; .........完整代码请登录后点击上方下载按钮下载查看
网友评论0