A replacement for binaryToBase64 that can be used in react-native

吃可爱长大的小学妹 提交于 2020-06-29 04:10:05

问题


I have been using react-native's binaryToBase64, but it doesn't exist in new react-native versions (such as 0.62.2).
Any suggestion on what to use instead?

I tried js btoa(), but results are different, any idea why?

For example:

btoa

let output = btoa(input);

input: Uint8Array(5) [0, 1, 2, 3, 4]
output: MCwxLDIsMyw0

input: Uint8Array(5) [5, 6, 7, 8, 9]
output: NSw2LDcsOCw5

binaryToBase64

let output = binaryToBase64(input);

input: Uint8Array(5) [0, 1, 2, 3, 4]
output: AAECAwQ=

input: Uint8Array(5) [5, 6, 7, 8, 9]
output: BQYHCAk=


回答1:


Answered here. Thanks, EyMaddis!

This is now more aligned with the rest of the JS ecosystem: base64.js:

import { Buffer } from 'buffer'

export function toBase64(input) {
  return Buffer.from(input, 'utf-8').toString('base64')
}

export function fromBase64(encoded) {
  return Buffer.from(encoded, 'base64').toString('utf8')
}


来源:https://stackoverflow.com/questions/62485527/a-replacement-for-binarytobase64-that-can-be-used-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!