Created
April 1, 2019 19:53
-
-
Save muhozi/5bba6898a337918313a10f1f2bd25f7e to your computer and use it in GitHub Desktop.
Upload image react native firebase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uploadImage = () => { | |
const ext = this.state.imageUri.split('.').pop(); // Extract image extension | |
const filename = `${uuid()}.${ext}`; // Generate unique name | |
this.setState({ uploading: true }); | |
firebase | |
.storage() | |
.ref(`tutorials/images/${filename}`) | |
.putFile(this.state.imageUri) | |
.on( | |
firebase.storage.TaskEvent.STATE_CHANGED, | |
snapshot => { | |
let state = {}; | |
state = { | |
...state, | |
progress: (snapshot.bytesTransferred / snapshot.totalBytes) * 100 // Calculate progress percentage | |
}; | |
if (snapshot.state === firebase.storage.TaskState.SUCCESS) { | |
const allImages = this.state.images; | |
allImages.push(snapshot.downloadURL); | |
state = { | |
...state, | |
uploading: false, | |
imgSource: '', | |
imageUri: '', | |
progress: 0, | |
images: allImages | |
}; | |
AsyncStorage.setItem('images', JSON.stringify(allImages)); | |
} | |
this.setState(state); | |
}, | |
error => { | |
unsubscribe(); | |
alert('Sorry, Try again.'); | |
} | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment