概述对大文件进行分块校验并续写可提升可靠性。本文给出分块摘要与 OPFS 续写示例。分块摘要与续写async function sha256(bytes) { const buf = await crypto.subtle.digest('SHA-256', bytes); return Array.from(new Uint8Array(buf)).map(x=>x.toString(16).padStart(2,'0')).join(''); } function openDB(name) { return new Promise((resolve, reject) => { const r = indexedDB.open(name, 1); r.onupgradeneeded = () => { const db = r.result; if (!db.objectStoreNames.contains('progress')) db.createObjectStore('progress'); }; r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); }); } async function saveProgress(key, val) { const db = await openDB('resume'); const tx = db.transaction('progress','readwrite'); tx.objectStore('progress').put(val, key); await new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); }); db.close(); } async function loadProgress(key) { const db = await openDB('resume'); const tx = db.transaction('progress','readonly'); const req = tx.objectStore('progress').get(key); const v = await new Promise((res, rej) => { req.onsuccess = () => res(req.result||{ index:0 }); req.onerror = () => rej(req.error); }); db.close(); return v; } async function resumeWrite(file, path, size = 1024*1024) { const root = await navigator.storage.getDirectory(); const fh = await root.getFileHandle(path, { create: true }); const ws = await fh.createWritable(); const prog = await loadProgress(path); let o = prog.index * size; let idx = prog.index; while (o < file.size) { const b = file.slice(o, o + size); const ab = await b.arrayBuffer(); const hex = await sha256(new Uint8Array(ab)); await ws.write(new Uint8Array(ab)); idx++; o += size; await saveProgress(path, { index: idx, lastChunkHash: hex }); } await ws.close(); }

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部