HTML5 IndexedDB - 如何将所有记录合并为一个

时间:2014-07-15 18:52:22

标签: javascript html5 indexeddb savefiledialog chunks

我的想法是从服务器下载一个巨大的文件块。

  1. 存储到IndexedDB中的块。

  2. 下载所有块后,将所有记录合并为一个(如SQL SELECT * FROM XXX ...)。

  3. 保存到磁盘" saveAs()"或创建IndexedDB的URL ......
  4. (或任何想法?)

    我不知道如何做第2步和第3步。

    (下面是在DB中存储10,000条记录并在步骤2之后存储预期输出的示例。应该是SusanSusanSusanSusanSusan ......)

    if (transaction) {
        transaction.oncomplete = function () {
        }
        transaction.onabort = function () {
            writeToConsoleScreen("transaction aborted.");
            localDatabase.db.close();
        }
        transaction.ontimeout = function () {
            writeToConsoleScreen("transaction timeout.");
            localDatabase.db.close();
        }
        var store = transaction.objectStore(osTableName);
        if (store) {
            var req;
            var customer = {};                   
           // create ten thousand records
           for (var loop = 0; loop < 10000; loop++) {
                customer = {};
                customer.fname = 'Susan';
                req = store.add(customer);
                req.onsuccess = function (ev) {
                }
                req.onerror = function (ev) {
                    writeToConsoleScreen("Failed to add record." + "  Error: " + ev.message);
                }
            }     
        }
    }
    

1 个答案:

答案 0 :(得分:2)

<!DOCTYPE html>
<script>
var open = indexedDB.open('chunks-example');
open.onupgradeneeded = function() {
  // Create schema if necessary
  var db = open.result;
  db.createObjectStore('chunks');
};

// 1. Chunks stored into an IndexedDB.
open.onsuccess = function() {
  var db = open.result;
  var tx = db.transaction('chunks', 'readwrite');
  var store = tx.objectStore('chunks');
  for (var i = 0; i < 10; ++i) {
    // For realz, this would be via
    // XMLHttpRequest.response and async.
    var chunk = new Blob(['chunk ' + i + '\n'],
      {type: 'application/octet-stream'});
    store.put(chunk, i);
  }
  tx.oncomplete = function() { merge(db); };
};

// 2. After "download" all chunks, merge all records into one
function merge(db) {
  var tx = db.transaction('chunks');
  var store = tx.objectStore('chunks');
  var chunks = [];
  var request = store.openCursor();
  request.onsuccess = function() {
    var cursor = request.result;
    if (cursor) {
      chunks.push(cursor.value);
      cursor.continue();
    } else {
      saveAs('myfile', new Blob(chunks,
        {type: 'application/octet-stream'}));
    }
  };
}

// 3. Save into disk "saveAs()"
function saveAs(filename, blob) {
  var a = document.documentElement.appendChild(document.createElement('a'));
  a.href = URL.createObjectURL(blob);
  a.download = filename;
  a.click();
  a.parentElement.remove(a);
}
</script>