Skip to content

Instantly share code, notes, and snippets.

@rjuevesano
Last active April 21, 2018 09:15
Show Gist options
  • Save rjuevesano/9a6a9fb7aa3c47d2a1e5a993f0ab4a16 to your computer and use it in GitHub Desktop.
Save rjuevesano/9a6a9fb7aa3c47d2a1e5a993f0ab4a16 to your computer and use it in GitHub Desktop.
Upload a base64 image with Firebase Storage
import { Platform } from 'react-native'
import ImagePicker from 'react-native-image-picker'
import RNFetchBlob from 'react-native-fetch-blob'
import firebase from 'firebase'
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
// add this to your action in adding a photo
ImagePicker.launchImageLibrary({}, response => {
uploadImage(response.uri)
.then(url => this.setState({ uploadURL: url }))
.catch(error => console.log(error))
})
const uploadImage = (uri, mime = 'application/octet-stream') => {
return new Promise((resolve, reject) => {
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
let uploadBlob = null;
const storageRef = firebase.storage().ref();
const imageRef = storageRef.child(YOUR_PATH);
fs.readFile(uploadUri, 'base64')
.then(data => {
return Blob.build(data, { type: `${mime};BASE64` });
})
.then(blob => {
uploadBlob = blob;
return imageRef.put(blob, { contentType: mime });
})
.then(() => {
uploadBlob.close();
return imageRef.getDownloadURL();
})
.then(url => resolve(url))
.catch(error => reject(error));
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment