2

我有超过 5MB 的数据需要存储在会话存储中。为此,我使用 pako 来压缩数据。

首先,我们有一个 Angular 应用程序,它从 API 接收数据并将其添加到哈希“cachedLookups”中:

const stringifiedLookups = JSON.stringify(this.cachedLookups)
const compressedLookups = new TextDecoder().decode(pako.deflate(stringifiedLookups));
sessionStorage.setItem(this.sessionStorageKey, compressedLookups);

然后我们在同一个浏览器窗口中有一个 AngularJS 应用程序,它从会话存储中检索这些数据:

const compressedLookups = localStorageService.get("cachedLookups");
const compressedLookupsUint8Array = new TextEncoder().encode(compressedLookups);
const stringifiedLookups = pako.inflate(compressedLookupsUint8Array, { to: 'string' });

当我点击 pako.inflate 时,我得到“不正确的标题检查”。我也尝试过 inflateRaw,在这种情况下我得到“无效的存储块长度”。我在这里使用 TextEncoder/Decoder,因为尝试将 Uint8Array 直接存储到 SessionStorage 会强制 SessionStorage 超出其配额,尽管计算的大小低于 5MB。我认为这个问题与 Storage API 是关于存储键值字符串对的事实有关。

4

1 回答 1

2

当您对 zip 文件进行编码/解码时,似乎 zip 标头会导致错误,因为 pako 返回的 Uint8Array 和 TextEncoder 返回的值不同。

var data = "a";
var deflated = pako.deflate(data)

var textEncoded = new TextDecoder().decode(deflated)
var binary = new TextEncoder().encode(textEncoded)


// Not the same
console.log(deflated)
console.log(binary)

// ERROR
console.log(pako.inflate(binary))

相反,如果您使用不添加 zip 标头的 deflateRaw 它工作得很好

var data = "a";
var deflated = pako.deflateRaw(data)

var textEncoded = new TextDecoder().decode(deflated)
var binary = new TextEncoder().encode(textEncoded)

// Same content
console.log(deflated)
console.log(binary)

// SUCCESS
console.log(pako.inflateRaw(binary, {to: 'string'}))
于 2021-07-06T21:20:32.367 回答