Get base64 String From File URL On React Native App
While working on the react native app, sometimes we need to get the base64 string from the file(image/video) URL. There are many packages available that convert a URL to base64 but they are not producing expected results. Finally, I have tried the “rn-fetch-blob” library and I was able to get the expected results.
The rn-fetch-blob library provides many file system and network functions that make file access and transfer of file data easier and more efficient for React Native developers.
Installations:npm install --save rn-fetch-blob
For ios: if using CocoaPods, add the below text to your Podfilepod 'rn-fetch-blob',
:path => '../node_modules/rn-fetch-blob'
If you are using the 0.29.2+ version of react-native then run the below commandreact-native link rn-fetch-blob
As for projects < 0.29 you need "rnpm" to link native packagesrnpm link
Usage:
Add the following two lines at the top of your file:import RNFetchBlob from "rn-fetch-blob";
const fs = RNFetchBlob.fs;
And add the below code into your function where you want to convert the file from URL to base64 string.let imagePath = "https://miro.medium.com/max/1856/1*TV0dKZKjMjp1J7b9oW58Rg.jpeg";
// set the image/video path here
RNFetchBlob.config({
fileCache: true
}).fetch("GET", imagePath) // the file is now downloaded at local storage
.then(resp => {
imagePath = resp.path(); // to get the file path
return resp.readFile("base64"); // to get the base64 string
})
.then(base64 => {
// here base64 encoded file data is returned
this.setState({base64Data: base64});
return fs.unlink(imagePath); // to remove the file from local storage
});
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.
Originally published at https://blog.webnersolutions.com on July 9, 2021.