indexedDB 使用场景以及简单上手

indexedDB 作为web端的数据库已经出现了好几年了,网上相关的资料一搜一箩筐,这里就不做详细的介绍了。按照我的理解就是一个前端js 可操作的数据库,允许前端做多格式和大容量的本地缓存,解决localstorage容量少(只有几M)储存格式单一(只能是字符串)的问题。

使用场景

一般情况下,需要用到本地缓存的大多都只是储存一些用户的基本信息,或者是一些可以给用户自定义的配置信息,基本都不会很大,localstorage 就能很好解决。
我目前遇到可以使用indexedDB 的唯一场景就是储存多图片的二进制blob 数据。具体的业务场景是这样的,在一个可以上传多图片的富文本编辑器中,图片的上传需要附带多个表单信息,有些表单属性是必须唯一的,造成无法批量上传图片,只能每次弹窗一个表单去提交一张图片。


151.png

而且,为了避免重复提交而给服务端创造过多的垃圾数据,在进行表单提交前还必须要对所有的图片进行MD5 的校验。去确认那些图片的是服务器没有的可以进行提交,并建立一个可提交图片列表弹窗。


778.png

45645.png

就在提交表单的时候遇到了一个不大不小的问题。提交表单是需要重新去获取图片的blob 二进制数据去提交的,而图片的二进制数据其实在前面的MD5验证的时候就已经可以获取得到的,所以这里没有必要再进行一次获取过程(因为这个过程会需要重复下载图片和转换的,而且遇到跨域的图片还会需要通过请求后端才能获取到图片的数据,这么做是比较浪费时间的)。更好的办法是在前面MD5校验的时候就把图片的blob 数据存放起来。常规的办法是直接存放到对象中,但毫无疑问一旦要存放的图片过多就会导致内存资源被大量占用,页面会变得非常卡顿。此时就轮到indexedDB 发光发热了。

// 本地图片数据库, md5 为主键,{md5:md5, src: src, file: file},
// 主要是用于在富文本校验图片的绑定情况的时候,解决由于吧file 存放于对象中使得内存占用过大而导致表单输入时卡顿的问题
export default class imgsDB {
  constructor(arg) {
    const that = this
    const request = window.indexedDB.open('imgs')
    request.onsuccess = function(e) {
      that.db = request.result
      console.log(e)
      console.log('打开数据库成功')
    }
    request.onerror = function(e) {
      console.log(e)
      console.log('打开数据库失败')
    }
    request.onupgradeneeded = function(event) {
      that.db = event.target.result
      let objectStore
      if (!that.db.objectStoreNames.contains('imgs')) {
        objectStore = that.db.createObjectStore('imgs', { keyPath: 'md5' }) // 新建表
        objectStore.createIndex('src', 'src', { unique: true })
        objectStore.createIndex('file', 'file', { unique: true })
      }
    }
  }

  read(md5) {
    const that = this
    return new Promise((res, rej) => {
      const transaction = that.db.transaction(['imgs'])
      const objectStore = transaction.objectStore('imgs')
      const request = objectStore.get(md5)

      request.onerror = function(event) {
        console.log('事务失败')
        rej()
      }
      request.onsuccess = function(event) {
        console.log(event)
        if (request.result) {
          res(request.result.file)
        } else {
          console.log('未获得数据记录')
        }
      }
    })
  }

  add(obj) {
    const that = this
    return new Promise((res, rej) => {
      const request = that.db.transaction(['imgs'], 'readwrite')
        .objectStore('imgs')
        .add(obj)

      request.onsuccess = function (event) {
        console.log(event)
        console.log('数据写入成功')
        res()
      }

      request.onerror = function (event) {
        console.log(event)
        console.log('数据写入失败')
        rej()
      }
    })
  }

  clear() {
    this.db.transaction(['imgs'], 'readwrite').objectStore('imgs').clear()
  }
}

setGridData(obj) {   // 根据遍历富文本生成图片的src_alt_list,补全md5等数据
      const that = this
      //let imgsdb = new imgsDB() 
      async function ergodic(obj) {
        let newGD = {}
        const arr = obj.bs64.split(',')
        const   mine = arr[0].match(/:(.*?);/)[1]
        const   bstr = atob(arr[1])
        let n = bstr.length
        const   u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        const boldData = new Blob([u8arr], { type: mine })
        const md5 = await that.md5(boldData, 1024*1024)
        let alt = obj.alt ? obj.alt : +new Date()
        let bs64 = obj.bs64
        let fileName = alt+ '.' + mine.split('/')[1]
        let file = new File([boldData], fileName, {type: mine})
        let src = obj.src
        that.imgsdb.add({md5, src, file})  // 吧图片数据存放到本地数据库中
        newGD = {md5, src, fileName, file}
        return newGD
      }
      let gd = ergodic(obj)
      return gd
    },
this.$refs['newbb'].validate((isOk, obj) => {
        if(isOk) {
          let fd = new FormData()
          fd.append('remark', that.form.remark)
          that.imgsdb.read(that.activeMedia.md5).then(res => {  // 从本地数据库中读取图片数据
            fd.append('file', res)
            $.ajax({
              type: 'post',
              url: ajaxIp,
              data: fd,
              contentType: false, // 告诉jQuery不要去设置Content-Type请求头
              processData: false, // 告诉jQuery不要去处理发送的数据
              success: function(res) {
                let data = res.data
                if (res.result == 'true') {
                  that.$message({ message: res.message, type: 'success' })
                } else {
                  that.$message({ message: res.message, type: 'warning' })
                }
              }
            })
          })

        }
      })
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容