使用HTML5 IndexDB存储图像和文件的示例


Posted in HTML / CSS onNovember 05, 2018

有一天,我们写了关于如何在localStorage中保存图像和文件的文章,它是关于我们今天可用的实用主义。 然而,localStorage有一些性能影响 - 我们将在稍后的博客中讨论这个问题 - 并且未来期望的方法是使用IndexedDB。 在这里,我将向您介绍如何在IndexedDB中存储图像和文件,然后通过ObjectURL呈现它们。

本文是翻译过来的,原文在这里 Storing images and files in IndexedDB

关于作者: Robert Nyman [Editor emeritus]

Technical Evangelist & Editor of Mozilla Hacks. Gives talks & blogs about HTML5, JavaScript & the Open Web. Robert is a strong believer in HTML5 and the Open Web and has been working since 1999 with Front End development for the web - in Sweden and in New York City. He regularly also blogs atrobertnyman.com and loves to travel and meet people.

使用IndexDB存储图像和文件的常规步骤

首先,我们来谈谈我们将创建一个IndexedDB数据库,将文件保存到其中然后将其读出并显示在页面中的步骤:

1、创建或打开数据库
2、创建一个objectStore
3、将图像文件检索为blob
4、初始化一个数据库事物
5、保存图像blob到数据库中去
6、读出保存的文件并从中创建ObjectURL并将其设置为页面中图像元素的src

1、创建或打开数据库。

// IndexedDB
window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB,
    IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction,
    dbVersion = 1;

/* 
    Note: The recommended way to do this is assigning it to window.indexedDB,
    to avoid potential issues in the global scope when web browsers start 
    removing prefixes in their implementations.
    You can assign it to a varible, like var indexedDB… but then you have 
    to make sure that the code is contained within a function.
*/

// Create/open database
var request = indexedDB.open("elephantFiles", dbVersion);

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

使用它的预期方法是在创建数据库时触发onupgradeneeded事件或获取更高版本号。 目前仅在Firefox中支持此功能,但很快将在其他Web浏览器中支持。 如果Web浏览器不支持此事件,则可以使用已弃用的setVersion方法并连接到其onsuccess事件。

2、创建一个objectStore(如果它尚不存在)

// Create an objectStore
console.log("Creating objectStore")
dataBase.createObjectStore("elephants");

在这里,您创建一个ObjectStore,您将存储数据 - 或者在我们的例子中,文件 - 并且一旦创建,您不需要重新创建它,只需更新其内容即可。

3、将图像文件检索为blob

// 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");
        
        // File as response
        blob = xhr.response;

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

此代码直接将文件的内容作为blob获取。目前只支持Firefox。 收到整个文件后,将blob发送到函数以将其存储在数据库中。

4、初始化一个数据库事物

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

要开始向数据库写入内容,您需要使用objectStore名称和要执行的操作类型(在本例中为read和write)启动事务。

5、保存图像blob到数据库中去

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

一旦事务到位,您将获得对所需objectStore的引用,然后将您的blob放入其中并为其提供密钥。

6、读出保存的文件并从中创建ObjectURL并将其设置为页面中图像元素的src

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

使用相同的事务来获取刚刚存储的图像文件,然后创建一个objectURL并将其设置为页面中图像的src。 例如,这也可以是一个附加到脚本元素的JavaScript文件,然后它将解析JavaScript。

最后完整代码

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

浏览器支持

URL API支持性

使用HTML5 IndexDB存储图像和文件的示例

indexDb

使用HTML5 IndexDB存储图像和文件的示例

Github源码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

HTML / CSS 相关文章推荐
对CSS3选择器的研究(详解)
Sep 16 HTML / CSS
纯CSS打造(无图像无js)的非常流行的讲话(语音)气泡效果
Dec 28 HTML / CSS
css3发光搜索表单分享
Apr 11 HTML / CSS
用纯css3实现的图片放大镜特效效果非常不错
Sep 02 HTML / CSS
CSS3中伪元素::before和::after的用法示例
Sep 18 HTML / CSS
如何开发一款堪比APP的微信小程序(腾讯内部团队分享)
Dec 22 HTML / CSS
使用Html5、CSS实现文字阴影效果
Jan 17 HTML / CSS
详解Html5中video标签那些属性和方法
Jul 01 HTML / CSS
HTML5 语义化结构化规范化
Oct 17 HTML / CSS
HTML5之语义标签介绍
Jul 07 HTML / CSS
CSS3 制作的书本翻页特效
Apr 13 HTML / CSS
HTML5中的DOCUMENT.VISIBILITYSTATE属性详解
May 07 HTML / CSS
canvas像素画板的实现代码
Nov 21 #HTML / CSS
详解使用canvas保存网页为pdf文件支持跨域
Nov 23 #HTML / CSS
websocket+sockjs+stompjs详解及实例代码
Nov 30 #HTML / CSS
HTML5中通过li-canvas轻松实现单图、多图、圆角图绘制,单行文字、多行文字等
Nov 30 #HTML / CSS
HTML5 Geolocation API的正确使用方法
Dec 04 #HTML / CSS
canvas实现俄罗斯方块的方法示例
Dec 13 #HTML / CSS
localStorage 设置过期时间的方法实现
Dec 21 #HTML / CSS
You might like
php桌面中心(二) 数据库写入
2007/03/11 PHP
用PHP实现浏览器点击下载TXT文档的方法详解
2013/06/02 PHP
PHP快速按行读取CSV大文件的封装类分享(也适用于其它超大文本文件)
2014/04/10 PHP
ThinkPHP中关联查询实例
2014/12/02 PHP
php冒泡排序与快速排序实例详解
2015/12/07 PHP
ThinkPHP框架实现导出excel数据的方法示例【基于PHPExcel】
2018/05/12 PHP
微信公众平台开发教程①获取用户Openid及个人信息图文详解
2019/04/10 PHP
jquery调用wcf并展示出数据的方法
2011/07/07 Javascript
一个仿糯米弹框效果demo
2014/07/22 Javascript
node.js中的console.log方法使用说明
2014/12/09 Javascript
Jquery插件之Fancybox丰富的弹出层效果附源码下载
2015/12/02 Javascript
onmouseover事件和onmouseout事件全面理解
2016/08/15 Javascript
AngularJS入门教程之路由机制ngRoute实例分析
2016/12/13 Javascript
Element Table的row-class-name无效与动态高亮显示选中行背景色
2018/11/30 Javascript
微信小程序实现页面下拉刷新和上拉加载功能详解
2018/12/03 Javascript
NodeJs操作MongoDB教程之分页功能以及常见问题
2019/04/09 NodeJs
jQuery开发仿QQ版音乐播放器
2020/07/10 jQuery
vue路由的配置和页面切换详解
2020/09/09 Javascript
Python单元测试框架unittest使用方法讲解
2015/04/13 Python
将Python代码嵌入C++程序进行编写的实例
2015/07/31 Python
Python设计模式编程中解释器模式的简单程序示例分享
2016/03/02 Python
python编写简单爬虫资料汇总
2016/03/22 Python
TensorFlow实现Batch Normalization
2018/03/08 Python
python学生信息管理系统(初级版)
2018/10/17 Python
[原创]Python入门教程1. 基本运算【四则运算、变量、math模块等】
2018/10/28 Python
如何使用python爬虫爬取要登陆的网站
2019/07/12 Python
PyCharm上安装Package的实现(以pandas为例)
2020/09/18 Python
设计模式的基本要素是什么
2014/04/21 面试题
市优秀教师事迹材料
2014/02/05 职场文书
财务会计自荐信范文
2014/02/21 职场文书
会计系毕业求职信
2014/08/07 职场文书
买房子个人收入证明
2014/10/12 职场文书
手机销售员岗位职责
2015/04/11 职场文书
教师研修随笔感言
2015/11/18 职场文书
Python基础之hashlib模块详解
2021/05/06 Python
Windows server 2012 NTP时间同步的实现
2022/06/25 Servers