Chrome Dev 已在 IndexedDB 上开始支持 Blob。
这是一项期待已久的功能,让 IndexedDB API 能够存储和检索 Blob,而无需将其转换为 Base64 字符串。
IndexedDB 提供大多数现代浏览器都支持的大规模键值对类型永久性存储(Safari 明显将支持 iOS8 和 Mac OS X 10.10)。请查看其实现状态。
Blob 是现代 JavaScript 引擎可以处理的类似于文件的二进制对象。File 对象继承自 Blob。您还可以通过 XMLHttpRequest 以 Blob 形式提取图片和文件。请查看其实现状态。
在 IndexedDB 上存储 Blob
无法在 IndexedDB 中通过功能检测 Blob 可用性。您基本上必须进行 try-catch,然后在字符串不可用时使用 string 而不是 Blob。以下是一些代码示例:
// Create an example Blob object
var blob = new Blob(['blob object'], {type: 'text/plain'});
try {
var store = db.transaction(['entries'], 'readwrite').objectStore('entries');
// Store the object
var req = store.put(blob, 'blob');
req.onerror = function(e) {
console.log(e);
};
req.onsuccess = function(event) {
console.log('Successfully stored a blob as Blob.');
};
} catch (e) {
var reader = new FileReader();
reader.onload = function(event) {
// After exception, you have to start over from getting transaction.
var store = db.transaction(['entries'], 'readwrite').objectStore('entries');
// Obtain DataURL string
var data = event.target.result;
var req = store.put(data, 'blob');
req.onerror = function(e) {
console.log(e);
};
req.onsuccess = function(event) {
console.log('Successfully stored a blob as String.');
};
};
// Convert Blob into DataURL string
reader.readAsDataURL(blob);
}
Firefox 和 Internet Explorer 中也已经提供了对 IndexedDB 的 Blob 支持。需要调查 Safari 是否支持。
祝你观看愉快!