Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert base64 into Blob in React Native?

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?

like image 610
wagng Avatar asked Apr 18 '16 15:04

wagng


People also ask

How do you convert base64 to blob in react?

You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array constructor. const byteArray = new Uint8Array(byteNumbers); This in turn can be converted to a BLOB by wrapping it in an array and passing it to the Blob constructor.

Can we store base64 in blob?

BLOBs stored in Spreadsheet Data Model files MUST be encoded by using base64 encoding prior to any other compression and storage. For information about the Spreadsheet Data Model file format, see section 2.1.

How do I convert to base64 in react native?

import base64 from 'react-native-base64' ... base64. encode('Some string to encode to base64'); base64. decode('SW4gbXkgZXllcywgaW5kaXNwb3NlZA0KSW4gZGlzZ3Vpc2VzIG5vIG9uZSBrbm93cw0KUklQIEND=='); base64.


1 Answers

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 :)

like image 78
Xeijp Avatar answered Sep 19 '22 09:09

Xeijp