How can you encode a string to Base64 in JavaScript?

前端 未结 26 3780
梦如初夏
梦如初夏 2020-11-21 04:02

I have a PHP script that can encode a PNG image to a Base64 string.

I\'d like to do the same thing using JavaScript. I know how to open files, but I\'m not sure how

26条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 05:08

    For newer browsers to encode Uint8Array to string, and decode string to Uint8Array.

    const base64 = {
        decode: s => Uint8Array.from(atob(s), c => c.charCodeAt(0)),
        encode: b => btoa(String.fromCharCode(...new Uint8Array(b)))
    };
    

    For Node.js you can use the following to encode string, Buffer, or Uint8Array to string, and decode from string, Buffer, or Uint8Array to Buffer.

    const base64 = {
        decode: s => Buffer.from(s, 'base64'),
        encode: b => Buffer.from(b).toString('base64')
    };
    

提交回复
热议问题