0
votes

I am trying to get the downloadURL from an image I have uploaded. With this function I upload the image to Firebase Storage

uploadImage() {
  this.image = 'movie-' + new Date().getTime() + '.jpg';
  let storageRef: any,
  parseUpload: any;
  return new Promise((resolve, reject) => {
  storageRef = firebase.storage().ref('imgs/' + this.image);
  parseUpload = storageRef.putString(this.cameraImage, 'data_url');     
})

The thing is that I want to save the image URL so I can take it from a document on Firestore. In order to do so I have this function to get the dowloadURL once the image is uploaded.

If I am not wrong this method should return an string, correct me If I am wrong, because If it isn't I would not be able to save it on Firestore

async getImgFromServer(imgName: string) {
  let img;
  let downloadIMG;
  img = firebase.storage().ref("/imgs/" + imgName).getDownloadURL();
  let ref= firebase.storage().ref();
  const imgRef = ref.child("/imgs/" + imgName);
  const downloadURL = await imgRef.getDownloadURL()
  return downloadURL
}

The only problem is that in order to do so, the image must be uploaded. I know this function will always return the url if the image is uploaded. The thing is that I dont know how to make this function work when the uploadImage() is complete. After getting the the url this is my function to save the url on the Firestore Cloud database.

 updateImgFromServer(image,id){
  this.firestore.doc(`public/${id}`).set({
    img:image,
  });
 }

Is there a way to ensure that the second function(getImgFromServer()) will be execute only after the first one(uploadImage()) has finished?

I know that there are ways to get the downloadURL once the file is uploaded on the first snippet I put. If anyone knows how to make it work It would fine too.

1

1 Answers

1
votes

putString() is asynchronous and returns an UploadTask that tracks the progress of the upload, which you need to use. It has a then() method which works just like a promise, so use that to determine when the upload is complete.