从 Firebase 存储中获取 getDownloadURL() 字符串 [英] get the getDownloadURL() String from Firebase Storage

查看:28
本文介绍了从 Firebase 存储中获取 getDownloadURL() 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取 getDownloadURL() 应该返回的 url.然而,它实际上是在向我返回数据,例如 this.

我已经设法在 html 上显示它,但我的真正目的是获取可以在我发布的图像上看到的 URL,因此我可以获取它并将其保存在我的 Firestore 数据库中.但是我不知道如何获得该值.这是我的片段:

 getImgFromServer(imgName: string): string {让img;让下载IMG;img = firebase.storage().ref("/imgs/" + imgName).getDownloadURL();让 ref= firebase.storage().ref();const imgRef = ref.child("/imgs/" + imgName);imgRef.getDownloadURL().then(function(url){下载IMG=网址;img = 下载IMG;console.log("我的网址" + downloadIMG)})控制台.log("img")控制台日志(img)返回图片}

调试此日志时,此代码打印出我要使用的 URL:

console.log("我的 URL" + downloadIMG)

<块引用>

我的网址 https://firebasestorage.googleapis.com/v0/b/static-epigram-189720.appspot.com/o/imgs%2Fmovie-1543700476524.jpg?alt=media&token=5550a552-1ed0-488e-beed-a6bc82791293

然而,这个打印来自 图像的数据:

console.log(img)

我想单独返回 URL,以便我可以使用它.

<块引用>

编辑

现在我获得了 URL,我想将它保存在 Cloud Firestore 中,这样我就可以使用 HTML 上的 URL 来显示图片.这是存储图像名称的函数:

createPublic(id,img){this.firestore.doc(`public/${id}`).set({图像,});}

有了Frank给出的答案,现在我可以获取URL了,所以我只是用它来获取URL并使用以下功能,更新我刚刚上传的文档.

 异步 updateImg(img,idPubli){const imgToUpdate= 等待 this.imgServ.getImgFromServer(img);this.imgServ.updateImgFromServer(imgToUpdate,idPubli)}updateImgFromServer(图像,ID){this.firestore.doc(`public/${id}`).set({图像:图像,});}

但它似乎不起作用.我可以想象这可能是因为在执行 updateImg() 之前尚未上传图像或文档,但我对异步函数有点陌生,所以我无法获得解决方案现在.

如果有帮助,这是我上传图片的功能和上传图片的功能.

 提交() {this.imgServ.uploadImage();this.viewCtrl.dismiss({data});}

在dismiss函数之后,我收集所有数据,然后调用createPublic()函数.

 uploadImage() {this.image = 'movie-' + new Date().getTime() + '.jpg';让 storageRef: any,解析上传:任何;return new Promise((resolve, reject) => {storageRef = firebase.storage().ref('imgs/' + this.image);parseUpload = storageRef.putString(this.cameraImage, 'data_url');parseUpload.on('state_changed', (_snapshot) => {//如果有必要,我们可以在这里记录进度//console.log('快照进程' + _snapshot);},(_err) =>{拒绝(_err);},(成功)=>{解决(解析上传.快照);});});}

解决方案

由于下载 URL 是通过调用服务器生成的,可能需要一些时间才能使用.而且您不能让代码等待该值可用.这就是为什么 getDownloadURL() 返回一个 promise,然后在从服务器获取下载 URL 后调用它的 then().此 URL 仅在回调中可用,因为回调之后的代码在服务器返回下载 URL 之前运行(因此在调用 then() 回调之前).

一种常见的方法是只传递promise,并在需要值时使用它的then().所以:

const imgRef = ref.child("/imgs/" + imgName);常量 downloadUrl = imgRef.getDownloadURL();...downloadUrl.then(函数(url){console.log("我的网址" + url)})

现代环境中的替代方法是使用新的 async/await 关键字.这些将上述基于承诺的方法包装在一些语法糖中:

async getImgFromServer(imgName: string): string {让img;让下载IMG;img = firebase.storage().ref("/imgs/" + imgName).getDownloadURL();让 ref= firebase.storage().ref();const imgRef = ref.child("/imgs/" + imgName);const downloadURL = 等待 imgRef.getDownloadURL()返回下载地址}

然后你称之为:

const downloadURL = await getImgFromServer("图像名称")

另见:

I am trying to get the url that getDownloadURL() should return. However it is in fact returning me data like this.

I have manage to display it on the html, however my real purpose is to get the URL, that can be seen on the image I posted, so I can get it and save it on my Firestore Database. However I dont know how to get that value. This is my snipet:

    getImgFromServer(imgName: string): string {
    let img;
    let downloadIMG;
    img = firebase.storage().ref("/imgs/" + imgName).getDownloadURL();
    let ref= firebase.storage().ref();
    const imgRef = ref.child("/imgs/" + imgName);
    imgRef.getDownloadURL().then(function(url){
      downloadIMG=url;
      img = downloadIMG;
      console.log("MY URL " + downloadIMG)

    })
    console.log("img")
    console.log(img)
    return img
  }

When debugging this log, this code prints the URL I want to use:

console.log("MY URL " + downloadIMG)

MY URL https://firebasestorage.googleapis.com/v0/b/static-epigram-189720.appspot.com/o/imgs%2Fmovie-1543700476524.jpg?alt=media&token=5550a552-1ed0-488e-beed-a6bc82791293

However this one, prints the data from the image :

console.log(img)

I would like to return the URL alone so I can use it.

EDIT

Now that I am getting the URL I would like to save it on the Cloud Firestore so I can use the URL on the HTML to show the picture. This is the function that store the name of the image:

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

With the answer given by Frank, now I can get the URL, so I just use it to take the URL and with the following function, update the document that I have just uploaded.

    async updateImg(img,idPubli){
    const imgToUpdate= await this.imgServ.getImgFromServer(img);
    this.imgServ.updateImgFromServer(imgToUpdate,idPubli)
  }

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

However it seems that it is not working. I can imagine that this might be because either the image or the document havent been uploaded before the updateImg() is execute, but I am kinda new to async functions so I can't manage to get a solution rigth now.

In case it helps, this are the functions where I upload the image and the function that uploads it.

 submit() {
    this.imgServ.uploadImage();
    this.viewCtrl.dismiss({data});
  }

After the dismiss function, I gather all the dataand then call the createPublic() function.

 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');


      parseUpload.on('state_changed', (_snapshot) => {
        // We could log the progress here IF necessary
        // console.log('snapshot progess ' + _snapshot);
      },
        (_err) => {
          reject(_err);
        },
        (success) => {
          resolve(parseUpload.snapshot);
        });
    });
  }

解决方案

Since the download URL is generated by a call to the server, it may take some time before it's available. And you can't make the code wait for that value to be available. That's why getDownloadURL() returns a promise, and then calls its then() once it got the download URL back from the server. This URL is only available within the callback, because the code after the callback runs before the server has returned the download URL (and thus before the then() callback was called).

One common approaches is to just pass the promise around, and use its then() whenever you need the value. So:

const imgRef = ref.child("/imgs/" + imgName);
const downloadUrl = imgRef.getDownloadURL();

...

downloadUrl.then(function(url){
  console.log("MY URL " + url)
})

The alternative on modern environments is to use the new async/await keywords. These wrap the promise-based approach of above in some syntactic sugar:

async getImgFromServer(imgName: string): 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
}

Which you then call as:

const downloadURL = await getImgFromServer("image name")

Also see:

这篇关于从 Firebase 存储中获取 getDownloadURL() 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆