尝试在indexedDB中存储文件时出错“对象存储当前不支持blob值”

时间:2014-03-03 14:19:13

标签: javascript indexeddb

我正在尝试使用IndexedDB在javascript中存储以存储blob。 这是我的代码

var Storage = (function () {
    function Storage(callback) {
        var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB, IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction, dbVersion = 1.0;

        this.URL = window.URL || window.webkitURL;

        var request = indexedDB.open('files', dbVersion);
        var self = this;

        request.onerror = function (e) {
            console.log("Error creating/accessing IndexedDB database");
        };

        request.onsuccess = function (e) {
            console.log("Success creating/accessing IndexedDB database");
            self.db = request.result;

            self.db.onerror = function (event) {
                console.log("Error creating/accessing IndexedDB database");
            };

            // Interim solution for Google Chrome to create an objectStore. Will be deprecated
            if (self.db.setVersion) {
                if (self.db.version != dbVersion) {
                    var setVersion = self.db.setVersion(dbVersion);
                    setVersion.onsuccess = function () {
                        self.createObjectStore(self.db);
                        callback();
                    };
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };

        // For future use. Currently only in latest Firefox versions
        request.onupgradeneeded = function (e) {
            self.createObjectStore(e.target.result);
        };
    }
    Storage.prototype.createObjectStore = function (db) {
        console.log('Creating objectStore');
        db.createObjectStore('files');
    };

    Storage.prototype.putFile = function (fileName, blob) {
        console.log('Putting file in IndexedDB');
        var transaction = this.db.transaction(['files'], 'readwrite');
        var put = transaction.objectStore('files').put(blob, fileName);
    };

    return Storage;
})();

我正在使用它:

var storage = new Storage(function () {
    var blob = new Blob(['FooBar']);
    storage.putFile('test', blob);
});

在Chrome上我得到:

DataCloneError: Failed to execute 'put' on 'IDBObjectStore': The object store currently does not support blob values.

在Firefox上我得到:

[Exception... "Data provided to an operation does not meet requirements."  code: "0" nsresult: "0x80660005 (DataError)"  location: "<unknown>"]

我不明白出了什么问题。

1 个答案:

答案 0 :(得分:1)

我找到了问题的答案。好吧,我确实找到了解决问题的方法:&#34;如何在Firefox中永久存储文件?&#34;

我找到了一个文件系统后备:https://github.com/ebidel/idb.filesystem.js

效果很好。