代码之家  ›  专栏  ›  技术社区  ›  theroglu

如何使用javascript在浏览器中使用localstorage存储Uint8array

  •  0
  • theroglu  · 技术社区  · 6 年前

    所以我的代码是这样的:

    const ivBytes = window.crypto.getRandomValues(new Uint8Array(16));
    localStorage.setItem("iv",JSON.stringify(ivBytes))
    console.log("content of ivBytes:" + ivBytes)
    

    在另一节课上,我试图得到这样的数据,但它不起作用

    let array = JSON.parse(localStorage.getItem("iv"))
    console.log("the iv value we get is: " + ivBytes)
    

    但是当我尝试获取数组的内容时,它并没有给出ivBytes的确切内容。输出如下: enter image description here

    如何在浏览器中存储Uint8array,并在使用localStorage的其他类中以相同的方式获取它?提前谢谢。

    1 回复  |  直到 6 年前
        1
  •  4
  •   Kaiido NickSlash    4 年前

    很难。。。


    不要在本地存储中存储二进制数据



    但是,这里你想要存储的似乎只是从crypto API中随机生成的数字,既然它是一个非常小的数组缓冲区,那么。。。

    要将TypedArray字符串化以便它可以存储在localStorage中,您需要逐个提取所有值并将它们移动到一个数组中,或者,如果可用,只需调用Array.from(yourTypedArray)然后字符串化这个数组:

    const typedArray = new Uint8Array(16);
    crypto.getRandomValues(typedArray);
    const arr = Array.from // if available
      ? Array.from(typedArray) // use Array#from
      : [].map.call(typedArray, (v => v)); // otherwise map()
    // now stringify
    const str = JSON.stringify(arr);
    console.log(str);
    // localStorage.setItem('foo', str);
    
    // and to retrieve it...
    // const str = localStorage.getItem('foo');
    const retrievedArr = JSON.parse(str);
    const retrievedTypedArray = new Uint8Array(retrievedArr);
    console.log(retrievedTypedArray.byteLength);
    推荐文章