indexDB入门

引言:

常用浏览器缓存:

        1.cookie:大小不超过4kb,每次请求发回服务器

        2.SessionStorage:会话窗口缓存,大小在5mb左右,不能永久缓存

        3.localStorage:大小跟SessionStorage差不多,不提供搜索功能,不能建立自定义索引

        如果需要用大更大的缓存容量,以及要求存储图片模型等文件且在意性能,就需要用的我们的indexDB,它是浏览器提供的本地数据库,可以被网页脚本创建和操作,允许存贮大量数据,提供查找接口,能建立索引。

indexDB优点是:存储容量大,起码能存几百兆;支持异步操作;具有事务特点;

indexDB缺点是:不支持DO操作;不能跨域。

下面展示代码演示 indexDB 的相关操作

        创建indexDB数据库,增删查改等功能实现:

0.判断浏览器是否支持IndexDB

    function justifyIndexDEB(){
        if("indexedDB" in window) {
            // 支持
            console.log(" 支持indexedDB...");
            createindexDB();    //创建数据库,下面有定义
        } else {
            // 不支持
            console.log("不支持indexedDB...");
            window.indexedDB = window.mozIndexedDB || window.webkitIndexedDB;
        }
    }
 

1. 创建并打开数据库

  function createindexDB () {
    let dbName = 'helloIndexDB', version = 1, storeName = 'helloStore'

    let indexedDB = window.indexedDB
    let db
    const request = indexedDB.open(dbName, version)
    request.onsuccess = function (event) {
      db = event.target.result // 数据库对象
      console.log('数据库打开成功...')
    }

    request.onerror = function (event) {
      console.log('数据库打开失败...')
    }

    request.onupgradeneeded = function (event) {
      // 数据库创建或升级的时候会触发
      console.log('onupgradeneeded')
      db = event.target.result 
      let objectStore
      if (!db.objectStoreNames.contains(storeName)) {
        objectStore = db.createObjectStore(storeName, { keyPath: 'id' }) // 创建表
        // objectStore.createIndex('name', 'name', { unique: true }) // 创建索引 可以让你搜索任意字段
      }
    }
   }

2. 增加数据


function addData(db, storeName, data) {
  return new Promise((resolve, reject) => {
    let request = db.transaction([storeName], 'readwrite') // 事务对象 指定表格名称和操作模式("只读"或"读写")
      .objectStore(storeName) // 仓库对象
      .add(data)
 
    request.onsuccess = function(event) {
      resolve(event)
    }
 
    request.onerror = function(event) {
      throw new Error(event.target.error)
      reject(event)
    }
  })
}

3. 删除数据

  function delete(db, storeName, id) {
    let request = db.transaction([storeName], 'readwrite').objectStore(storeName).delete(id)

    request.onsuccess = function () {
      console.log('数据删除成功')
    }

    request.onerror = function () {
      console.log('数据删除失败')
    }
 

4.查找数据


  function get(db, storeName, key) {
      let transaction = db.transaction([storeName]) // 事务
      let objectStore = transaction.objectStore(storeName) // 仓库对象
      let request = objectStore.get(key)
 
      request.onerror = function(event) {
        console.log('事务失败')
      }
 
      request.onsuccess = function(event) {
        console.log('主键查询结果: ', request.result)
      }
  }

 

5.改变数据


  function update(db, storeName, data) {
    let request = db.transaction([storeName], 'readwrite') // 事务对象
      .objectStore(storeName) // 仓库对象
      .put(data)
 
    request.onsuccess = function() {
      console.log('数据更新成功')
    }
 
    request.onerror = function() {
      console.log('数据更新失败')
    }
  }
 
 

 实战:使用IndexedDB存储图像和文件      

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

    // Create/open database
    var request = indexedDB.open("elephantFiles", dbVersion),
        db,
        createObjectStore = function (dataBase) {
            // Create an objectStore
            console.log("Creating objectStore")
            dataBase.createObjectStore("elephants");
        },

        getImageFile = function () {
            // Create XHR
            var xhr = new XMLHttpRequest(),
                blob;

            xhr.open("GET", "elephant.png", true);
            // Set the responseType to blob
            xhr.responseType = "blob";

            xhr.addEventListener("load", function () {
                if (xhr.status === 200) {
                    console.log("Image retrieved");
                    
                    // Blob as response
                    blob = xhr.response;
                    console.log("Blob:" + blob);

                    // Put the received blob into IndexedDB
                    putElephantInDb(blob);
                }
            }, false);
            // Send XHR
            xhr.send();
        },

        putElephantInDb = function (blob) {
            console.log("Putting elephants in IndexedDB");

            // Open a transaction to the database
            var transaction = db.transaction(["elephants"], IDBTransaction.READ_WRITE);

            // Put the blob into the dabase
            var put = transaction.objectStore("elephants").put(blob, "image");

            // Retrieve the file that was just stored
            transaction.objectStore("elephants").get("image").onsuccess = function (event) {
                var imgFile = event.target.result;
                console.log("Got elephant!" + imgFile);

                // Get window.URL object
                var URL = window.URL || window.webkitURL;

                // Create and revoke ObjectURL
                var imgURL = URL.createObjectURL(imgFile);

                // Set img src to ObjectURL
                var imgElephant = document.getElementById("elephant");
                imgElephant.setAttribute("src", imgURL);

                // Revoking ObjectURL
                URL.revokeObjectURL(imgURL);
            };
        };

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

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

        db.onerror = function (event) {
            console.log("Error creating/accessing IndexedDB database");
        };
        
        // Interim solution for Google Chrome to create an objectStore. Will be deprecated
        if (db.setVersion) {
            if (db.version != dbVersion) {
                var setVersion = db.setVersion(dbVersion);
                setVersion.onsuccess = function () {
                    createObjectStore(db);
                    getImageFile();
                };
            }
            else {
                getImageFile();
            }
        }
        else {
            getImageFile();
        }
    }
    
    // For future use. Currently only in latest Firefox versions
    request.onupgradeneeded = function (event) {
        createObjectStore(event.target.result);
    };
})();


你可能感兴趣的:(浏览器原理与网络,数据库,前端)