HTML5中IndexedDB存储Blob文件对象或ArrayBuffer方案需要先看清适用场景和关键步骤,避免只记结论却忽略实际限制。
IndexedDB可直接高效存储Blob和ArrayBuffer,无需base64转换;存取时需保持类型一致、注意事务生命周期及键路径设计,并避免存储File对象或大文件超配额。
IndexedDB 可以直接存储 Blob 和 ArrayBuffer,无需转成 base64 或字符串,这是最高效、最推荐的方式。关键在于确保数据类型在存取过程中保持一致,并注意事务生命周期和对象存储(objectStore)的键路径设计。
Blob 是浏览器原生支持的二进制大对象,IndexedDB 完全兼容。只要 Blob 没被释放或回收(比如页面跳转前未持久化),就能正常写入和读取。
ArrayBuffer 同样被 IndexedDB 原生支持,比 Blob 更底层,适合处理音频、图像解码数据、加密结果等场景。
{ id: 2, data: buffer, type: "image/png", length: buffer.byteLength }
new Uint8Array(result.data)
IndexedDB 对二进制数据的处理很稳定,但几个边界点容易出错:
以下代码片段展示核心流程,不含错误处理和封装,便于理解本质逻辑:
const request = indexedDB.open("fileDB", 1);request.onupgradeneeded = e => { const db = e.target.result; if (!db.objectStoreNames.contains("files")) { db.createObjectStore("files", { keyPath: "id" }); }};request.onsuccess = e => { const db = e.target.result; const tx = db.transaction("files", "readwrite"); const store = tx.objectStore("files"); // 存储 Blob const blob = await fetch("/test.png").then(r => r.blob()); store.put({ id: 1, name: "test.png", file: blob }); // 读取并显示 store.get(1).onsuccess = e => { const record = e.target.result; const url = URL.createObjectURL(record.file); document.querySelector("img").src = url; };};