I am trying to upload Image using Firebase in Firebase Storage, but file doesn't uploads completely. It shows the size of image 9 bytes only, and when downloaded, it can't be previewed.
Here is the code i am using:-
const [image, setImage] = useState(null)
const [uploading, setUploading] = useState(false);
const [transferred, setTransferred] = useState(0);
const uploadImage = async () => {
if( image == null ) {
return null;
}
const uploadUri = image;
let filename = uploadUri.substring(uploadUri.lastIndexOf('/') + 1);
console.log(filename)
// Add timestamp to File Name
const extension = filename.split('.').pop();
const name = filename.split('.').slice(0, -1).join('.');
filename = name + Date.now() + '.' + extension;
console.log("filename")
console.log(filename)
setTransferred(0);
const storageRef = firebase.storage().ref(`photos/${filename}`);
console.log("storageRef")
const task = storageRef.put(uploadUri);
console.log("storageRef")
console.log(storageRef)
// Set transferred state
task.on('state_changed', (taskSnapshot) => {
console.log(
`${taskSnapshot.bytesTransferred} transferred out of ${taskSnapshot.totalBytes}`,
);
setTransferred(
Math.round(taskSnapshot.bytesTransferred / taskSnapshot.totalBytes) *
100,
);
console.log(transferred)
});
try {
await task;
const url = await storageRef.getDownloadURL();
setUploading(false);
setImage(null);
alert(
'Image uploaded!',
'Your image has been uploaded to the Firebase Cloud Storage Successfully!',
);
return url;
} catch (e) {
console.log(e);
return null;
}
};
const takephotofrommlib = () => {
ImagePicker.openPicker({
width: 300,
height: 300,
cropping: true,
}).then((image) => {
console.log(image);
const imageUri = Platform.OS === 'ios' ? image.path : image.path;
setImage(image.path);
console.log("image.path")
console.log(image.path)
});
};
I am using react-native-image-crop-picker. I am using Firebase but not react-native firebase. Please Help!
image
? I see you're checkingif (image === null)
at the beginning ofuploadImage
but I don't see whereimage
is defined? – Matt UstorageRef.putFile(uploadUri)
instead of justput
? – Matt U