Skip to content
Advertisement

Firebase Storage – Upload Image with React Native, Error loading Preview

This is the code which I use to upload images to firebase storage

const filename = image.substring(image.lastIndexOf('/') + 1);
const uploadUri = Platform.OS === 'ios' ? image.replace('file://', '') : image
var metadata = {
  contentType: 'image/jpeg',
};
const task = firebase.storage().ref().put(uploadUri, metadata)
try {
 await task
} catch(err) {
 console.log(err)
}

But when I check the firebase console it shows, error loading preview, and the file size is 9B for a image. Is there something Im missing. [Firebase Console Pic]

Im using Expo managed, expo-image-picker to select images.

Advertisement

Answer

I found a way, I had to create a blob and then upload the blob to firebase

    const filename = image.substring(image.lastIndexOf('/') + 1);

    const blob = await new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.onload = function() {
        resolve(xhr.response);
      };
      xhr.onerror = function() {
        reject(new TypeError("Network request failed"));
      };
      xhr.responseType = "blob";
      xhr.open("GET", image, true);
      xhr.send(null);
    });
    const ref = firebase
      .storage()
      .ref()
      .child(filename);
      
    const task = ref.put(blob, { contentType: 'image/jpeg' });

    task.on('state_changed', 
      (snapshot) => {
        console.log(snapshot.totalBytes)
      }, 
      (err) => {
        console.log(err)
      }, 
      () => {
        task.snapshot.ref.getDownloadURL().then((downloadURL) => {
          console.log(downloadURL);
      });
    })
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement