无法将blob保存到indexedDB

s4chpxco  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(2)|浏览(202)

我在IndexedDB中保存blob时遇到问题,并且只能使用blob。
如果我保存其他内容(如image as base64),则一切正常。
但是对于blob,只保存了空对象属性。

控制台屏幕截图:

代码:

//prepared blob...
var openRequest = indexedDB.open("testDB",1);

openRequest.onupgradeneeded = function(e) {
    var thisDB = e.target.result;

    if(!thisDB.objectStoreNames.contains("stash")) {
        thisDB.createObjectStore("stash");
    }
}

openRequest.onsuccess = function(e) {
    db = e.target.result;

    var transaction = db.transaction(["stash"],"readwrite");
    var store = transaction.objectStore("stash");
    var tID = Date.now();

    var obj = {
        bl:blob,
        created:tID
    }
    console.log(obj);
    //add it 
    var request = store.add(obj, tID);
    request.onerror = function(e) {
        console.log("Error",e.target.error.name);
    }
    request.onsuccess = function(e) {
        console.log("success");
    }
}
openRequest.onerror = function(e) {
    //....
}

我还尝试只保存blob(不 Package 为obj属性),这是相同的。
我可以将blob保存到HDD,如果我控制台记录我的obj,我会得到:

所以我猜,blob是有效的,问题是在将它添加到indexedDB中。我是blob/indexedDB的新手,可能会犯一些低级错误。
有人能告诉我,我做错了什么吗?
PS:完全没有错误消息

lrl1mhuk

lrl1mhuk1#

很老的问题,但现在支持在IndexedDb中保存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);
}

截至发布时,引用文档的最后更新日期为:Last updated 2019-03-20 UTC.

bybem2ql

bybem2ql2#

您可以将Blob或File对象转换为ArrayBuffer对象或二进制字符串,然后保存它在读取indexedDB后将其转换回Blob

//prepared blob...
blobToBlob2(blob, saveBlob2);

function blobToBlob2(blob, callback){
    var reader = new FileReader();
    reader.readAsArrayBuffer(blob);
    reader.onload = function(e) {
        callback({
            buffer: e.target.result,
            type: blob.type
        });
    };
}

function blob2ToBlob(blob2){
    return new Blob([blob2.buffer],{type:blob2.type});
}

function saveBlob2(blob2){
    //..... code
    var obj = {
        bl:blob2,
        created:tID
    }
    var request = store.add(obj, tID);
    //..... code
}

相关问题