You could use the buffer library to decode base64 encoded data in a react native app.
npm i buffer
Once installed you can import the buffer library into your react native app
import { Buffer } from 'buffer';
and then decode base64 encoded data
Buffer.from(data, 'base64');
The line above returns the decoded data as bytes and
Buffer.from(data, 'base64').toString('ascii');
returns the decoded data as an ascii encoded string.
Answer from Susanne on Stack OverflowRNFS.writeFile ?
import RNFS from 'react-native-fs';
RNFS.writeFile(RNFS.CachesDirectoryPath + '/a.jpeg', base64, 'base64')
// RNFS.CachesDirectoryPath + '/a.jpeg'
I've faced a similiar challenge in my past experience, from what my final conclusion was,handling multiple images with the base64 will be troublesome.
Even though you can display it,
var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANS...';
<Image style={{width: 50, height: 50}} source={{uri: base64Icon}}/>
but having 1000s of images will cause issues and there will be challenges like :
- Mobile phones has limitations on the RAM and processor speed.Sending 100 image base64 in a flatlist and rendering will slow down your phone and app significantly-- so not recommended.
- Your app , in such scenarios will consume a lot of memory, and to process that proportionally fast phone memory is required -- so its not recommended
- Your overall UI/UX will be very bad , as if apps are slow and dont give the feel of native, your ratings and downloads will drop.
So it's best that you host your images from the backend in cloudinary etc, and just send the URI in thumbnail instead of the whole base64.
Hope that helps. feel free for doubts
React-Native: Convert image url to base64 string
How to convert base64 image data to data URL in react native?
Join the Expo Developers Discord Server!
React-native decoded base64 encoded string - Stack Overflow
» npm install react-native-base64
I use rn-fetch-blob, basically it provides lot of file system and network functions make transferring data pretty easy.
react-native-fetch-blob is deprecated
import RNFetchBlob from "rn-fetch-blob";
const fs = RNFetchBlob.fs;
let imagePath = null;
RNFetchBlob.config({
fileCache: true
})
.fetch("GET", "http://www.example.com/image.png")
// the image is now dowloaded to device's storage
.then(resp => {
// the image path you can use it directly with Image component
imagePath = resp.path();
return resp.readFile("base64");
})
.then(base64Data => {
// here's base64 encoded image
console.log(base64Data);
// remove the file from storage
return fs.unlink(imagePath);
});
source Project Wiki
There is a better way: Install this react-native-fs, IF you don't already have it.
import RNFS from 'react-native-fs';
RNFS.readFile(this.state.imagePath, 'base64')
.then(res =>{
console.log(res);
});
I find some simple way worked for me, the same api as node.
Install buffer
yarn add buffer
Usage:
console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));
atob and btoa are not supported in JavascriptCore but works when the app runs under Chrome debugger, because JS code runs in Chrome when debugged. There are many base64 modules. https://github.com/mathiasbynens/base64 works fine for me.
» npm install react-native-image-base64
I ended up using react-native-blob-util
const res = await DocumentPicker.pickSingle({
type: [
DocumentPicker.types.images,
DocumentPicker.types.pdf,
DocumentPicker.types.docx,
DocumentPicker.types.zip,
],
});
const newUploadedFile: IUploadedFile[] = [];
const fileType = res.type;
if (fileType) {
const fileExtension = fileType.substr(fileType.indexOf('/') + 1);
const realURI = Platform.select({
android: res.uri,
ios: decodeURI(res.uri),
});
if (realURI) {
const b64 = await ReactNativeBlobUtil.fs.readFile(
realURI,
'base64',
);
const filename = res.name.replace(/\s/g, '');
const path = uuid.v4();
newUploadedFile.push({
name: filename,
type: fileType,
size: res.size as number,
extension: fileExtension,
blob: b64,
path: Array.isArray(path) ? path.join() : path,
});
} else {
throw new Error('Failed to process file');
}
} else {
throw new Error('Failed to process file');
}
You don't need to the third-party package to fetch BLOB data
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", "[LOCAL_FILE_PATH]", true);
xhr.send(null);
});
// Code to submit blob file to server
// We're done with the blob, close and release it
blob.close();
» npm install react-native-image-to-base64