Reputation: 11
I'm using this method to try upload image to Firebase with my React-Native app because it seems to be a very common example on the internet, However I think it is quite old and I suspect that it no longer works on newer versions of React-Native.
Can someone please show me the correct way to save images in Firebase storage, thank you!
const uploadImage = (uri, imageName, mime = 'image/jpg') => {
return new Promise((resolve, reject) => {
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '')
: uri;
let uploadBlob = null
const imageRef = firebase.storage().ref('images/').child(imageName)
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)})
})
}
Upvotes: 1
Views: 2924
Reputation: 1431
You can just use the putFile method.
Here is my FirebaseStorageService with saveImage method (I'm using RN 0.53 and react-native-firebase 4.1.0):
saveImage(ref, image, imageName, onSuccess, onError){
LOG.debug("FirebaseStorageService :: saveImage ", {ref:ref, image:image, imageName:imageName});
var firebaseStorageRef = firebase.storage().ref(ref);
const imageRef = firebaseStorageRef.child(imageName + ".jpeg");
LOG.debug("FirebaseStorageService :: imageRef ", {imageRef:imageRef});
imageRef.putFile(image.path, {contentType: 'image/jpeg'}).then(function(){
return imageRef.getDownloadURL();
}).then(function(url){
LOG.debug("Image url", {url:url});
onSuccess(url);
}).catch(function(error){
LOG.error("Error while saving the image.. ", error);
onError(error);
});
}
The image is the one returned by react-native-image-crop-picker. User can choose between open camera and open gallery and it returns an image object.
The path property of the image object is just a string like "file://.." for Android and "/Users/..." for iOS.
Upvotes: 1