Chrome Dev で IndexedDB の Blob サポートを開始

Eiji Kitamura
Eiji Kitamura

Chrome Dev の IndexedDB で Blob がサポートされるようになりました。

これは、待望の Chrome の機能です。IndexedDB API で Blob を Base64 文字列に変換することなく保存および取得できるようになります。

IndexedDB は、最新のブラウザのほとんどで利用できる、大規模な Key-Value 型の永続ストレージを提供します(Safari は iOS8 と Mac OS X 10.10 でサポートされる予定です)。実装ステータスをご確認ください。

Blob は、最新の JavaScript エンジンで処理できるファイルのようなバイナリ オブジェクトです。File オブジェクトは Blob から継承されます。XMLHttpRequest を使用して、画像やファイルを Blob として取得することもできます。実装ステータスをご確認ください。

IndexedDB に Blob を保存する

IndexedDB で Blob の可用性を検出する機能はありません。Blob ではなく string が使用できない場合は、try-catch を使用する必要があります。サンプルコードを以下に示します。

// 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);
}

IndexedDB の Blob サポートは、Firefox と Internet Explorer でもすでに提供されています。Safari のサポート状況を調査する必要があります。

ぜひご利用ください。