//调整webkit兼容性
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB,
   IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction,
   dbVersion = 1.0;
 
var cn,db;
 
//打开数据库
//第一个参数是数据库名(打开即创建,没有其它独立的创建方法)
//其它参数以后解释
var cn=indexedDB.open("item" );
 
//数据库初始化事件
cn.onupgradeneeded=function(e){
  //获取数据库对象
  db=e.target.result;
  //创建数据库实例
  //第一个是存储对象名,类似关系数据库的表名
  //第二个参数是主键名,还有其他选项,可以设置自增的
  var o=db.createObjectStore(
    "PicData",{keyPath: "id"}
  );
};
 
//数据库打开成功事件
cn.onsuccess=function(e){
  //获取数据库对象
  //因为上面的初始化事件未必会被调用到,这里当然也得获取一次
  db=e.target.result;
  //这个doTransaction的参数是一个回调函数,可以把这个回调函数当作事物的过程使用
  db.doTransaction=function(f){
    //从事务对象闪使用objectStore访问具体的存储对象,并把结果传给回调函数
    f(db.transaction("PicData" ,"readwrite" ).objectStore("PicData"));
  };
};
 
// 将图片缓存的本地
 function fetchImage(id, type) {
     var src = ""
     var imageId = id;
     if (type == "small") {
          src = "../item/common/simpleImage.do?picId=" +id;
     } else {
          src = "../item/common/simpleImage.do?type=b&picId=" +id;
          imageId = (id+ "blimg");
     }
     
     var elephant = document.getElementById(id);
     elephant.src = "../item/img/loading.gif";
     try {
         var readWriteMode = typeof IDBTransaction.READ_WRITE == "undefined" ? "readwrite" : IDBTransaction.READ_WRITE;
           var transaction = db.transaction(["PicData" ], readWriteMode);
               
           var objectStore = transaction.objectStore("PicData" );
           var request = objectStore.get(imageId);
          request.onsuccess = function(event) {
               var data = event.target.result;
               if (data == null) {
                 // Create XHR
                 var xhr = new XMLHttpRequest(),
                     blob;
          
                 xhr.open( "GET", src, true );
                 // Set the responseType to blob
                 xhr.responseType = "blob";
                
                 xhr.addEventListener( "load", function () {
                     if (xhr.status === 200) {
                           // Blob as response
                          blob = xhr.response;
                          var imgFile = blob;
              
                          // Get window.URL object
                          var URL = window.URL || window.webkitURL;
              
                          // Create and revoke ObjectURL
                          var imgURL = URL.createObjectURL(imgFile);
              
                          // Set img src to ObjectURL
                          elephant.setAttribute( "src", imgURL);
              
                          // Revoking ObjectURL
                          elephant.onload = function() {
                              window.URL.revokeObjectURL(this .src);
                          }
                         // Save data in indexDB
                         var picData = {};
                         picData.id = imageId;
                          picData.blob = blob;
                          saveInIndexDB(picData);
                     }
                 }, false);
                 // Send XHR
                 xhr.send();
              } else {
                      console.log( "Got image !");
          
                      // Get window.URL object
                      var URL = window.URL || window.webkitURL;
          
                      // Create and revoke ObjectURL
                      var imgURL = URL.createObjectURL(request.result.blob);
          
                         // Set img src to ObjectURL
                        Imagess(imgURL,id);
                      //elephant.setAttribute("src", imgURL);
          
                      // Revoking ObjectURL
                      elephant.onload = function() {
                          window.URL.revokeObjectURL(this .src);
                      }
              }
          }
     } catch (e) {
           Imagess(src, id);
     }
}
 
function saveInIndexDB(picData) {
  //调用我们自己添加的方法来处理一个事务
  db.doTransaction(function(e){
     e.add(picData);
  });
}
 
//判断是否加载完成 
function Imagess(url,imgid){     
    var img= new Image(); 
    img.src = url;
   
    //判断浏览器 
     var Browser= new Object(); 
     Browser.userAgent=window.navigator.userAgent.toLowerCase(); 
     Browser.ie= /msie/.test(Browser.userAgent); 
     Browser.Moz= /gecko/.test(Browser.userAgent); 
     
    if(Browser.ie){ 
        img.onreadystatechange = function(){   
            if(img.readyState=="complete" ||img.readyState=="loaded"){ 
                document.getElementById(imgid).src=img.src;
            } 
        }         
    }else if(Browser.Moz){ 
        img.onload= function(){ 
            if(img.complete==true){ 
                document.getElementById(imgid).src=img.src;
            } 
        }         
    }     
}
 
// 缓存数据
function getItemPicId (currentPage) {
     $.ajax({
          type: "post",
          url: "../item/common/cacheItemPic.do" ,
          data:{ "currentPage":currentPage},
          dataType: "json",
          error: function(){
          },
          success: function(data){
              cacheItemPic(data.rows);
              total = data.total;
          }
     });
}
 
// 保存到本地
function cacheItemPic(data) {
     for ( var i=0; i < data.length; i++) {
                var src = ""
               var imageId = data[i].ST_PIC_ID;
               if (data[i].NM_SORT == "1" ) {
                   src = "../item/common/simpleImage.do?picId=" +imageId;
                   cacheImg (imageId, src);
              }
              src = "../item/common/simpleImage.do?type=b&picId=" +imageId;
              imageId = (imageId+ "blimg");
              cacheImg (imageId, src);
     }
     
     function cacheImg (imgId, imgSrc) {
           try {
              var readWriteMode = typeof IDBTransaction.READ_WRITE == "undefined" ? "readwrite" : IDBTransaction.READ_WRITE;
               var transaction = db.transaction(["PicData" ], readWriteMode);
                    
               var objectStore = transaction.objectStore("PicData" );
               var request = objectStore.get(imgId);
              request.onsuccess = function(event) {
                    var data = event.target.result;
                    if (data == null) {
                      // Create XHR
                     var xhr = new XMLHttpRequest(),
                         blob;
              
                     xhr.open( "GET", imgSrc, true);
                     // Set the responseType to blob
                     xhr.responseType = "blob";
                    
                     xhr.addEventListener( "load", function () {
                         if (xhr.status === 200) {
                                // Blob as response
                              blob = xhr.response;
                               var imgFile = blob;
                   
                              // Save data in indexDB
                             var picData = {};
                             picData.id = imgId;
                               picData.blob = blob;
                               saveInIndexDB(picData);
                         }
                     }, false);
                     // Send XHR
                     xhr.send();
                   } else {
                        console.log( "Got image !");
                        objectStore. delete(imgId);
                        console.log( "delete data!");
                           // Create XHR
                          var xhr = new XMLHttpRequest(),
                              blob;
                   
                          xhr.open( "GET", imgSrc, true);
                          // Set the responseType to blob
                          xhr.responseType = "blob";
                         
                          xhr.addEventListener( "load", function () {
                              if (xhr.status === 200) {
                                    // Blob as response
                                   blob = xhr.response;
                                    var imgFile = blob;
                        
                                   // Save data in indexDB
                                  var picData = {};
                                  picData.id = imgId;
                                    picData.blob = blob;
                                    saveInIndexDB(picData);
                              }
                          }, false);
                          // Send XHR
                          xhr.send();
                   }
              }
          } catch (e) {
                console.log( "cache image error!");
          }
     }
}

indexDB的使用和异步图片blob文件保存的更多相关文章

  1. HTML5预览图片、异步上传文件

    注意啦:本文的代码都是以JQuery为示例,jq_开头的变量都是jq对象. 在HTML5中,我们可以在图片上传之前对图片进行预览,就像下面这么做 jq_upload_file.change(funct ...

  2. struts2 jquery ajaxFileUpload 异步上传文件

    网上搜集的,整理一下. 一.ajaxFileUpload 实现异步上传文件利用到了ajaxFileUpload.js这个文件,这是别人开发的一个jquery的插件,可以实现文件的上传并能够和strut ...

  3. 关于js异步上传文件

    好久没登录博客园了,今天来一发分享. 最近项目里有个需求,上传文件(好吧,这种需求很常见,这也不是第一次遇到了).当时第一想法就是直接用form表单提交(原谅我以前就是这么干的),不过表单里不仅有文件 ...

  4. 【转】JQuery插件ajaxFileUpload 异步上传文件(PHP版)

    前几天想在手机端做个异步上传图片的功能,平时用的比较多的JQuery图片上传插件是Uploadify这个插件,效果很不错,但是由于手机不支持flash,所以不得不再找一个文件上传插件来用了.后来发现a ...

  5. 异步上传文件,ajax上传文件,jQuery插件之ajaxFileUpload

    http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html 一.ajaxFileUpload是一个异步上传文件的jQuery插件. ...

  6. iOS异步图片加载优化与常用开源库分析

    网络图片显示大体步骤: 1.下载图片: 2.图片处理(裁剪,边框等): 3.写入磁盘: 4.从磁盘读取数据到内核缓冲区: 5.从内核缓冲区复制到用户空间(内存级别拷贝): 6.解压缩为位图(耗cpu较 ...

  7. HTML5 jQuery+FormData 异步上传文件,带进度条

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href ...

  8. iOS学习笔记之异步图片下载

    写在前面 在iOS开发中,无论是在UITableView还是在UICollectionView中,通过网络获取图片设置到cell上是较为常见的需求.尽管有很多现存的第三方库可以将下载和缓存功能都封装好 ...

  9. 异步图片下载引擎(升级版——ExecutorService+handler)

    [Android分享] 异步图片下载引擎(升级版——ExecutorService+handler)  [复制链接]     皮诺 13 主题 5 好友 844 积分 No.4 中级开发者 升级  2 ...

随机推荐

  1. python's fifteenth day for me 递归函数

    递归... def age(n): if n == 1: return 18 else: return age(n-1)+2 # 反复调用函数age() print(age(4)) l = [1,3, ...

  2. python写一个能生成三种一句话木马的脚本

    代码: import time import os from threading import Thread import optparse def aspyijuhua(): try: juy=op ...

  3. DRF - 序列化组件(GET/PUT/DELETE接口设计)、视图优化组件

    一.序列化组件 基于上篇随笔的表结构 , 通过序列化组件的ModelSerializer设计如下三个接口 : GET 127.0.0.1:8000/books/{id} # 获取一条数据,返回值:{} ...

  4. zookeeper java api(使用java代码操作zookeeper)

    1 导入相关的pom依赖 <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId&g ...

  5. SpringMVC简单的文件上传

    引入依赖包: <!-- 文件上传的依赖 --> <dependency> <groupId>commons-fileupload</groupId> & ...

  6. 深入剖析SolrCloud(一)

    作者:洞庭散人 出处:http://phinecos.cnblogs.com/ 本博客遵从Creative Commons Attribution 3.0 License,若用于非商业目的,您可以自由 ...

  7. 玩转Mysql命令

    连接数据库mysql -hlocalhost -uroot -p 在MYsql的跟目录文件下进行 show databses:展示所有数据库 解决方法1:在MySql安装目录下找到my.ini,将[m ...

  8. java用JDBC连接数据库的方式

    //驱动位置String sDBDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//连接数据库地址名字String ...

  9. Linux中IO监控命令的使用分析

    一篇不错的有关linux io监控命令的介绍和使用. 1.系统级IO监控 iostat iostat -xdm 1    # 个人习惯 %util         代表磁盘繁忙程度.100% 表示磁盘 ...

  10. k阶原点距和k阶中心距各是说明什么数字特征

    k阶原点距和k阶中心距各是说明什么数字特征 二阶中心距,也叫作方差,它告诉我们一个随机变量在它均值附近波动的大小,方差越大,波动性越大.方差也相当于机械运动中以重心为转轴的转动惯量.(The mome ...