0
votes

I am trying to display the image from firebase storage. Below is the file location copied from firebase storage. It is a jpeg file

profile/2186uPKjgo4pMOQNm0Cm/profilepic

My following code returned error.

useEffect(() => {

function geturl(){
  
  const filename = "profile/"+userid+"/profilepic.jpeg";
  var ref = firebase.storage().ref(filename);
  console.log(filename);
  // This returns the exact file name
  ref.getDownloadURL().then((url)=> {
    console.log(url);
  });
  
}
geturl();
}, []);

I got this error [object Object]. After that, I tried the following code async await

useEffect(() => {

async function geturl(){
  
  const filename = "profile/"+userid+"/profilepic.jpeg";
  var ref = firebase.storage().ref(filename);
  console.log("inside geturl");
  const downloadurl = await ref.getDownloadURL();
  console.log(downloadurl);
}
geturl();
}, []);

Now Im getting the following error.

Possible Unhandled Promise Rejection (id: 29):
"code_": "storage/object-not-found",
  "message_": "Firebase Storage: Object 'profile/2186uPKjgo4pMOQNm0Cm/profilepic.jpeg' does not exist.",
  "name_": "FirebaseError",
  "serverResponse_": "{
  \"error\": {
    \"code\": 404,
    \"message\": \"Not Found.  Could not get object\",
    \"status\": \"GET_OBJECT\"
  }
}",
}

Please let me know how I can get the url?

1

1 Answers

0
votes

here you go you can use this function it uploads image to firebase storage and get the image uri at the same time

const uploadImage = async () => {
        const response = await fetch(image);
        const blob = await response.blob();
        let filename = image.substring(image.lastIndexOf('/')+1);
        const ext = filename.split('.').pop();
        const name = filename.split('.').slice(0, -1).join('.');
        filename = name + Date.now() + '.' + ext;
        try {
            var ref = firebase.storage().ref().child('post-images/'+filename);
            await ref.put(blob)
            .then(snapshot => {
                return snapshot.ref.getDownloadURL(); 
            })
            .then(downloadURL => {
                console.log(`Successfully uploaded file and got download link');
                return downloadURL;
            });
            return null;
        } catch (error) {
            return null;
        }  
    }