使用IndexedDB存储图像和文件

有一天,我们写了关于如何在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 at http://robertnyman.com and loves to travel and meet people.

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

首先,我们来谈谈我们将创建一个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 deprecatedif (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 responseblob = xhr.response;// Put the received blob into IndexedDBputElephantInDb(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 objectvar URL = window.URL || window.webkitURL;// Create and revoke ObjectURLvar imgURL = URL.createObjectURL(imgFile);// Set img src to ObjectURLvar imgElephant = document.getElementById("elephant");imgElephant.setAttribute("src", imgURL);// Revoking ObjectURLURL.revokeObjectURL(imgURL);
};

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

最后完整代码

(function () {// IndexedDBvar 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 databasevar 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 responseblob = xhr.response;console.log("Blob:"   blob);// Put the received blob into IndexedDBputElephantInDb(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 objectvar URL = window.URL || window.webkitURL;// Create and revoke ObjectURLvar imgURL = URL.createObjectURL(imgFile);// Set img src to ObjectURLvar imgElephant = document.getElementById("elephant");imgElephant.setAttribute("src", imgURL);// Revoking ObjectURLURL.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 deprecatedif (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);};
})();

浏览器支持

  • URL API支持性

  • indexDb

Github源码

使用HTML5 IndexDB存储图像和文件相关推荐

  1. python图片保存为txt文件_python + opencv实现提取png图像的像素信息并存储到txt文件中(附安装指导)...

    相关库安装指导: 这里我们需要 opencv_python,numpy,matplotlib库,另外我用的是python3.6.1版本. 一般库大家都是用pip install命令安装的,不过不知道为 ...

  2. 神奇的HTML5离线存储(应用程序缓存)

    声明:本文为原创文章,如需转载,请注明来源并保留原文链接前端小尚,谢谢! 前言 使用 HTML5,通过创建 cache manifest 文件,可以轻松地创建 web 应用的离线版本. HTML5引入 ...

  3. 在DB中存储图像-是或否?

    因此,我正在使用一个将图像大量存储在数据库中的应用程序. 您对此有何看法? 我更喜欢将位置存储在文件系统中,而不是直接将其存储在数据库中. 您认为优点/缺点是什么? #1楼 我尚未见任何人提及的一件事 ...

  4. HTML5 本地存储

    HTML5 本地存储 1.sessionStorage 2.localStorage 3.Database Storage 4.globalStorage 5.兼容性 参考文献 本地持久化存储一直是本 ...

  5. html5离线保存需要联网吗,html5 离线存储

    在html页面中引入manifest文件 在服务器添加mime-type text/cache-manifest 如下: sample.appcache内容如下: CACHE MANIFEST #ve ...

  6. 如何存储 Git 大文件?

    作者:terryshchen,腾讯 IEG 应用开发工程师 本文主要讲解在 Git 仓库中如何管理大的二进制文件,详细介绍了什么是 Git LFS,Git LFS 是如何工作的,以及如何使用 Git ...

  7. HTML5本地存储不完全指南

    历史 在HTML5本地存储之前,如果我们想在客户端保存持久化数据,有这么几个选择: HTTP cookie.HTTP cookie的缺点很明显,最多只能存储4KB的数据,每个HTTP请求都会被传送回服 ...

  8. html5访问本地资源,HTML5实现一个访问本地文件的实例今

    怎么通过 html5 读取本地文件 看你要读取什么 在高深一点的要php html5 打开本地文件夹 我想在chrome浏览器下实现点击 打开文件夹 html5本地存储怎么做,html5本地存储实例详 ...

  9. php版canvas,PHP实现将HTML5中Canvas图像保存到服务器

    这篇文章主要介绍了PHP实现将HTML5中Canvas图像保存到服务器的方法,可实现将Canvas图像保存到服务器的功能,是非常实用的技巧,需要的朋友可以参考下 本文实例讲述了PHP实现将HTML5中 ...

最新文章

  1. 对某课程的建议和意见_2021年河南专升本专科专业对照和考试课程征求意见
  2. 主题已放宽,科研UP主们速来Bio-protocol破浪吧
  3. R—计算系统发育多样性PD (Calculate Faith’s Phylogenetic Diversity)
  4. 计算机的u盘显示桌面,U盘图示在我的电脑显示不出?
  5. 达梦数据库导入oracle数据_Java项目,从Oracle迁移到达梦数据库笔记
  6. 电脑技巧:键盘上ESC按键的使用小技巧,你都知道吗?
  7. 磁盘和文件系统管理一
  8. azw3转换为pdf_怎么合并几个PDF为一个?快用这个PDF转换器!
  9. Quartz的集群模式和单机模式共存-让一个非集群的Quartz与集群节点并行着运行
  10. session.setattribute 设置后取不到值_从入门到精通,别处学不到的污泥浓度计的使用和维护技巧...
  11. 团队作业3 需求分析与系统设计
  12. mysql之我们终将踩过的坑(优化)
  13. 智能推送LeetCode中文站点题目思路解析
  14. kafka从入门到精通:马士兵java集合
  15. ensp VLAN划分
  16. 磁盘如何除写保护(常规解决方案)
  17. 无人出租车江湖:百度出击,安途并进
  18. 苹果计算机密码bug,苹果iOS 13系统新BUG:快速输入密码,解锁无效
  19. 保障信息安全不违规,App应满足哪些法律规定
  20. 2014各大互联网前端面试题总结

热门文章

  1. Drawable Resources
  2. 「题解」:[组合数学]:Perm 排列计数
  3. lengthOfLongestSubstring
  4. JSON格式数据与数据组件
  5. 重装mysql出现无法start service的问题
  6. 2017/3/8 函数指针/事件/委托....
  7. linux 内核移植和根文件系统的制作【转载】
  8. Oracle11.2.0.4 RAC安装文档
  9. css3 transition的应用
  10. (Joomla)字符串截取