การสนับสนุน Blob สำหรับ IndexedDB มาถึงใน Chrome Dev แล้ว

Chrome Dev ได้รองรับ Blob ใน IndexedDB

ฟีเจอร์นี้เป็นฟีเจอร์รอคอยมานานสำหรับ Chrome ซึ่งจะช่วยให้ IndexedDB API สามารถจัดเก็บและเรียกข้อมูล Blob ได้โดยไม่ต้องแปลงเป็นสตริง Base64

IndexedDB มีพื้นที่เก็บข้อมูลถาวรประเภทคีย์-ค่าขนาดใหญ่ที่มีให้ใช้งานบนเบราว์เซอร์รุ่นใหม่ๆ ส่วนใหญ่ (ดูเหมือนว่า Safari จะรองรับใน iOS8 และ Mac OS X 10.10) ดูสถานะการติดตั้งใช้งาน

Blob คือออบเจ็กต์ไบนารีที่คล้ายไฟล์ซึ่งเครื่องมือ JavaScript สมัยใหม่สามารถจัดการได้ ออบเจ็กต์ไฟล์รับค่ามาจาก Blob คุณสามารถดึงข้อมูลรูปภาพและไฟล์เป็น Blob ผ่าน XMLHttpRequest ได้ด้วย ดูสถานะการติดตั้งใช้งาน

การจัดเก็บ Blob ใน IndexedDB

ไม่มีวิธีสำหรับฟีเจอร์เพื่อตรวจหาความพร้อมใช้งาน Blob ใน IndexedDB โดยทั่วไปแล้วคุณจะต้องลองใช้ catch แล้วใช้สตริงแทน 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);
}

การสนับสนุน Blob สำหรับ IndexedDB มีให้บริการแล้วใน Firefox และ Internet Explorer เช่นกัน ต้องมีการตรวจสอบการสนับสนุนของ Safari

ขอให้สนุกกับการรับชม