React-Native: Convert Image Url to Base64 String

React-Native: Convert image url to base64 string

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

how can i convert image uri to base64?

You can use react-native-fs if you are using react-native cli

documentation: https://github.com/itinance/react-native-fs#readfilefilepath-string-encoding-string-promisestring

import RNFS from 'react-native-fs';

//base64 res
var data = await RNFS.readFile( "file://path-to-file", 'base64').then(res => { return res });

How to convert Blob URL to Base64 string and retrieve an Image URL using Cloudinary Client-Side?

I've figured it out:

After a few hours, and some nice people posting on StackOverflow I have pieced it together.

const getBlobData = (file) => {
axios({
method: "get",
url: file, // blob url eg. blob:http://127.0.0.1:8000/e89c5d87-a634-4540-974c-30dc476825cc
responseType: "blob",
}).then(function (response) {
var reader = new FileReader();
reader.readAsDataURL(response.data);
reader.onloadend = function () {
var base64data = reader.result;
const formData = new FormData();
formData.append("file", base64data);
formData.append("api_key", YOUR_API_KEY);
// replace this with your upload preset name
formData.append("upload_preset", YOUR_PRESET_NAME);//via cloudinary
axios({
method: "POST",
url: "https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/upload",
data: formData,
})
.then((res) => {
const imageURL = res.data.url;
//YOU CAN SET_STATE HOWEVER YOU WOULD LIKE HERE.
})
.catch((err) => {
console.log(err);
});
};
});
};


Related Topics



Leave a reply



Submit