侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

数据库  /  管理员 发布于 5年前   216

有一天,我们写了关于如何在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、创建或打开数据库。

// IndexedDBwindow.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 databasevar 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 versionsrequest.onupgradeneeded = function (event) {    createObjectStore(event.target.result);};

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

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

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

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

3、将图像文件检索为blob

// Create XHRvar xhr = new XMLHttpRequest(),    blob;xhr.open("GET", "elephant.png", true);// Set the responseType to blobxhr.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 XHRxhr.send();

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

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

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

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

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

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

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

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

// Retrieve the file that was just storedtransaction.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 objectStoreconsole.log("Creating objectStore")dataBase.createObjectStore("elephants");        },        getImageFile = function () {// Create XHRvar xhr = new XMLHttpRequest(),    blob;xhr.open("GET", "elephant.png", true);// Set the responseType to blobxhr.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 XHRxhr.send();        },        putElephantInDb = function (blob) {console.log("Putting elephants in IndexedDB");// Open a transaction to the databasevar transaction = db.transaction(["elephants"], IDBTransaction.READ_WRITE);// Put the blob into the dabasevar put = transaction.objectStore("elephants").put(blob, "image");// Retrieve the file that was just storedtransaction.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支持性

indexDb

Github源码

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


  • 上一条:
    select不支持双击dbclick事件
    下一条:
    Web数据存储浅析 Cookie、UserData、SessionStorage、WebSqlDatabase
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客