Skip to content

Instantly share code, notes, and snippets.

@akinozgen
Created September 16, 2017 23:10
Show Gist options
  • Save akinozgen/e22a6d8e302ca259f2caa7033edc541a to your computer and use it in GitHub Desktop.
Save akinozgen/e22a6d8e302ca259f2caa7033edc541a to your computer and use it in GitHub Desktop.
ReactNative Firebase Image Upload
import React, { Component } from 'react';
import { AppRegistry, View, Text, Button } from 'react-native';
import firebase from 'firebase';
import ImagePicker from 'react-native-image-picker';
import RNFetchBlob from 'react-native-fetch-blob';
const firebaseConfig = {
apiKey: "AIzaSyAtsN21kfXEOzG-uYvDqwOnkPpNx9KP1s8",
authDomain: "fir-reactnative-ad507.firebaseapp.com",
databaseURL: "https://fir-reactnative-ad507.firebaseio.com",
projectId: "fir-reactnative-ad507",
storageBucket: "fir-reactnative-ad507.appspot.com",
messagingSenderId: "747510304962"
};
const filePickerConfig = {
title: 'Fotoğraf Seç',
storageOptions: {
skipBackup: true,
path: 'images'
}
}
export default class FirebaseReactNative extends Component {
state = {
user: null
}
storage = firebase.storage()
constructor(props) {
super(props);
firebase.initializeApp(firebaseConfig);
firebase.auth().signInAnonymously().catch(err => {
console.log("Login ERR:", err);
});
firebase.auth().onAuthStateChanged(user => {
this.setState({ 'user': user });
}).bind(this);
}
uploadPhoto() {
ImagePicker.showImagePicker(filePickerConfig, response => {
console.log('Response', response);
if (response.didCancel) {
alert('İptal edildi.');
} else if (response.error) {
alert('Hata. Konsola bak');
console.log(response.error);
} else {
let ref = firebase.storage().ref();
let Blob = RNFetchBlob.polyfill.Blob;
let fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
return new Promise((resolve, reject) => {
let uploadBlob = null;
let imageRef = firebase.storage().ref('/images/').child(response.fileName)
fs.readFile(response.path, 'base64').then(data => {
return Blob.build(data, { type: `${response.type};BASE64` })
}).then(blob => {
uploadBlob = blob;
return imageRef.put(blob, { contentType: response.type });
}).then(() => {
uploadBlob.close();
return imageRef.getDownloadURL();
}).then(url => resolve(url)).catch(err => reject(err));
});
}
});
}
render() {
return (
<View style={styles.root}>
<Button title="Fotoğraf Seç" onPress={this.uploadPhoto} />
</View>
);
}
}
const styles = {
root: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#efebe1',
height: '100%'
}
};
AppRegistry.registerComponent('FirebaseReactNative', () => FirebaseReactNative);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment