Convert blob to base64

后端 未结 9 2127
无人共我
无人共我 2020-11-22 13:12

This is a snippet for the code that I want to do Blob to Base64 string:

This commented part works and that when the URL generated by this i

9条回答
  •  一向
    一向 (楼主)
    2020-11-22 13:39

    function bufferToBinaryString(arrayBuffer){
        return String.fromCharCode(...new Uint8Array(arrayBuffer));
    }
    (async () => console.log(btoa(bufferToBinaryString(await new Response(blob).arrayBuffer()))))();
    

    or

    function bufferToBinaryString(arrayBuffer){
        return String.fromCharCode(...new Uint8Array(arrayBuffer));
    }
    new Response(blob).arrayBuffer().then(arr_buf => console.log(btoa(bufferToBinaryString(arr_buf)))))
    

    see Response's constructor, you can turn [blob, buffer source form data, readable stream, etc.] into Response, which can then be turned into [json, text, array buffer, blob] with async method/callbacks.

    edit: as @Ralph mentioned, turning everything into utf-8 string causes problems (unfortunately Response API doesn't provide a way converting to binary string), so array buffer is use as intermediate instead, which requires two more steps (converting it to byte array THEN to binary string), if you insist on using native btoa method.

提交回复
热议问题