20

I am going to convert b64 to blob in react native.

But I am getting error on atob function.

Here are my codes.

var binary = atob(this.state.avatarSource.uri.split(',')[1]);
var byteNumbers = new Array(binary.length);

for(var i = 0; i < binary.length; i++) {
  byteNumbers.push(binary.charCodeAt(i));
}
var file = new Blob([new Uint8Array(byteNumbers)], {type: 'image/jpeg'});

Anybody has any idea?

wagng
  • 691
  • 2
  • 11
  • 22
  • 1
    Did you ever figure this out? I'm having the same problem – pomo Apr 19 '16 at 08:52
  • Possible duplicate of [Creating a Blob from a base64 string in JavaScript](http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript) – Endless Nov 17 '16 at 08:07
  • not duplicate, react native uses `JavascriptCore` which for instance doesn't implement `atob` and `btoa` – Custodio Jul 29 '19 at 21:57

6 Answers6

10

Do not use atob or btoa, that only works in Debug Mode.

Because when you're using Debug Mode, you're running your JS code in browser (which should be V8), whereas if you're going to run the app in production mode it uses JavascriptCore which does not have an atob or btoa implementation.

You can use base-64 to convert data to BASE64 encoded string, but I'm not sure if it can create a correct Blob object for you.

From my understanding, Blob is an bridge between JS context and file system, React Native does not have file system API itself yet, therefore you might get a Blob object but it's always empty.

If you're going to create an image from array contains numbers, you have a look at react-native-fetch-blob which is a project I'm working on, hopefully it can solve this kind of problems :)

Xeijp
  • 853
  • 1
  • 7
  • 18
  • 3
    Does react-native-fetch-blob provides Blob? im currently using "react-native-image-picker" which provides URI and base64. I need to convert it into blob. Please provide a suggestion. – HungrySoul May 22 '18 at 07:08
  • react-native-fetch-blob solved this issue for me. Seems like it is a good solution if you have a base64 string you need to send to a http(s) post end point as it has built-in functionality for this conversion – Patrick Kelly Jun 08 '20 at 21:52
  • 2
    2021 here and react-native-fetch-blob, as well as the repository it further links to, are all unmaintained... there must be a way to convert a base64 to blob in 2021 right? – fullStackChris Sep 02 '21 at 20:59
  • The solution I posted was the only one that didn't produce a corrupted file – Sid Mar 05 '23 at 04:55
4

Ran into this situation where fetch() on Android will not work with a data URI. Instead, try the following:

import { Buffer } from "buffer";


const base64 = 'iVBORw0KGgoAAAANSUhEU ....'
const buffer = Buffer.from(base64, "base64");

const blob = new Blob([buffer], { type: '[content-type]' })

content-type here would be 'image/png' if the base64 was a PNG file.

BlueDevil2k6
  • 126
  • 4
1

right solution

1 = download this library npm i -S base-64

2= add this into import sction in your screen import {decode as atob, encode as btoa} from 'base-64';

3= set this function in your screen

  const dataURLtoFile = (dataurl, filename) => {
var arr = dataurl.split(','),
  mime = arr[0].match(/:(.*?);/)[1],
  bstr = atob(arr[1]),
  n = bstr.length,
  u8arr = new Uint8Array(n);

while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
}

return new File([u8arr], filename, {type: mime});
};

finally call this function

let file = dataURLtoFile(
                'data:image/png;base64,' + response.assets[0].base64, //if your bas64 include <data:image/png;base64,> rmove this from parameter 
                'test.png',
              );



console.log(file )

haaaa everything is ready

i hope this answer to help anyone

o M a R
  • 11
  • 1
0

Note that react native doesn't actually have Blobs - you can use the below code but note that the file will be loaded completely in memory so shouldn't be used for any large files. 'rn-fetch-blob' is the only library I have used that allows for native blobs - but it doesn't work with every package.

Note that the uri needs to be "file://path"

function uriToBlob(uri: string): Promise<Blob> {
return new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest()
  xhr.responseType = 'blob'
  xhr.onload = () => {
    const blob = xhr.response
    resolve(blob)
  }
  xhr.onerror = (err) => {
    reject(err)
  }
  xhr.open('GET', uri)
  xhr.send()
})}

Update: This also works for me

 const res = await fetch(`file://${segment.uri}`) 
 const blobData = await res.blob()
Sid
  • 846
  • 3
  • 12
  • 25
-1

I am getting the base 64 of an image. After that I am displaying it from below code. Hope it may help you

let imgSrc = "data:image/png;base64," + base64ImageData;
<Image source={{uri: imgSrc, scale: 1}} style={{ height: 80, width: 80}}/>
Jagadish Upadhyay
  • 1,236
  • 13
  • 22
-1

you could try fetch

  let blob = await this.base64ToBlob(encoded);
  console.log('btoB64 resp === ', blob);

  async base64ToBlob(encoded) {
    let url = `data:image/jpg;base64,${encoded}`;
    let res = await fetch(url);
    let blob = await res?.blob();
    return blob;
  }
Shabeer Ali
  • 903
  • 11
  • 20