Created
August 25, 2022 01:46
-
-
Save arshadazaad3/12f6ab43df4635d55d5a27f6a0d4c166 to your computer and use it in GitHub Desktop.
React Native Firebase Upload Image
This file contains 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(`common/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