简体   繁体   English

成功将图像上传到 Firebase 存储后,Firebase 获取下载 URL

[英]Firebase get Download URL after successful image upload to firebase storage

I am trying to upload a single image to Firebase Storage, then grab its download url and assign this to a variable.我正在尝试将单个图像上传到 Firebase 存储,然后获取其下载 url 并将其分配给一个变量。

I can upload my image to firebase successfully, however I cannot retrieve the download url.我可以成功地将我的图片上传到 Firebase,但是我无法检索下载网址。 here is what I have tried already.这是我已经尝试过的。

upload() {
    let storageRef = firebase.storage().ref();
    let success = false;

    for (let selectedFile of [(<HTMLInputElement>document.getElementById('file')).files[0]]) {
      let router = this.router;
      let af = this.af;
      let folder = this.folder;
      let path = `/${this.folder}/${selectedFile.name}`;
      var iRef = storageRef.child(path);
      iRef.put(selectedFile).then((snapshot) => {
        console.log('Uploaded a blob or file! Now storing the reference at', `/${this.folder}/images/`);
        af.list(`/${folder}/images/`).push({ path: path, filename: selectedFile.name })
      });
    }

    // This part does not work
    iRef.getDownloadURL().then((url) => {this.image = url});
    console.log('IREF IS ' + iRef)
    console.log('IMAGEURL IS ' + this.image)

  }

The Console logs are these:控制台日志如下:

    IREF IS gs://my-app-159520.appspot.com/images/Screen Shot 2017-08-14 at 12.19.01.png
    view-order.component.ts:134 IMAGEURL IS undefined
Uploaded a blob or file! Now storing the reference at /images/images/

I have been trying to use the iRef reference to grab the download url but I keep getting errors.我一直在尝试使用 iRef 参考来获取下载 url,但我不断收到错误。 I am trying to grab the url so I can assign it to the this.image variable and then store it in my database using another function.我正在尝试获取 url,以便可以将其分配给 this.image 变量,然后使用另一个函数将其存储在我的数据库中。

The API has changed. API 已更改。 Use the following to get downloadURL使用以下命令获取下载地址

  snapshot.ref.getDownloadURL().then(function(downloadURL) {
    console.log("File available at", downloadURL);
  });

I think I have figured this out and it seems to be working, I realised I had to grab the downloadURL from the snapshot and assign that to this.image like so:我想我已经想通了,它似乎正在工作,我意识到我必须从快照中获取 downloadURL 并将其分配给 this.image ,如下所示:

upload() {
    let storageRef = firebase.storage().ref();
    let success = false;

    for (let selectedFile of [(<HTMLInputElement>document.getElementById('file')).files[0]]) {
      let router = this.router;
      let af = this.af;
      let folder = this.folder;
      let path = `/${this.folder}/${selectedFile.name}`;
      var iRef = storageRef.child(path);
      iRef.put(selectedFile).then((snapshot) => {

        // added this part which as grabbed the download url from the pushed snapshot
        this.image = snapshot.downloadURL;

        console.log('Uploaded a blob or file! Now storing the reference at', `/${this.folder}/images/`);
        af.list(`/${folder}/images/`).push({ path: path, filename: selectedFile.name })

        console.log('DOWNLOAD URL IS ' + this.image)
      });
    }

  }

I then ran my other function to add the URL to the database and it has gone in ok where expected!然后我运行我的另一个函数将 URL 添加到数据库,它在预期的地方正常运行!

So I have uploaded the image to the database, then using the snapshot from the put function, I then assigned my variable image:any to to the snapshot downloadURL like so:因此,我已将图像上传到数据库,然后使用 put 函数中的快照,然后将变量 image:any 分配给快照 downloadURL,如下所示:

this.image = snapshot.downloadURL;

I hope this can help someone else!我希望这可以帮助别人!

In 2019, I gained access to the url of a newly-saved file in firebase with the following function:在 2019 年,我通过以下功能获得了对 firebase 中新保存文件的 url 的访问权限:

const uploadImage = async(uri) => {
  const response = await fetch(uri);
  const blob = await response.blob();
  // child arg specifies the name of the image in firebase
  const ref = firebase.storage().ref().child(guid());
  ref.put(blob).then(snapshot => {
    snapshot.ref.getDownloadURL().then(url => {
      console.log(' * new url', url)
    })
  })
}

.put() function is returning a task, which can be used to track the uploading state. .put()函数返回一个任务,可用于跟踪上传状态。

For example you can listen for progress, error or completion like so:例如,您可以像这样监听进度、错误或完成:

onUploadImage () {
  const self = this
  const file = self.selectedFile
  if (!file) {
    return
  }
  self.isUploading = true
  const storageRef = firebase.storage().ref('/images/' + file.name)
  const task = storageRef.put(file)
  task.on('state_changed',
    function progress (snapshot) {
      self.status = 'UPLOADING...'
      self.percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
    },
    function error () {
      self.status = 'FAILED TRY AGAIN!'
      self.isUploading = false
    },

    function complete (event) {
      self.status = 'UPLOAD COMPLETED'
      self.isUploading = false
      storageRef.getDownloadURL().then((url) => { console.log(url) })
    }
  )
}

As of web version v9 (modular) you can achieve this in this way:从 web 版本 v9(模块化)开始,您可以通过以下方式实现:

import { getStorage, ref, uploadBytes, getDownloadURL } from "firebase/storage"; 

uploadImage = () => {
  const storage = getStorage()
  const reference = ref(storage, 'file_name.jpg')
  const file = e.target.files[0]

  uploadBytes(reference, file)
    .then(snapshot => {
      return getDownloadURL(snapshot.ref)
    })
    .then(downloadURL => {
      console.log('Download URL', downloadURL)
    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试将图像上传到 firebase 存储并获取下载 url - I'm trying to upload an image to firebase storage and get the download url 如何将图像上传到 firebase 存储,然后返回下载 url? - How to upload an image to firebase storage and then return the download url? Firebase 存储图像上传 - 上传后返回图像 URL 的函数 - Firebase Storage Image upload - Function to return the Image URL after uploading it Web Firebase从存储中获取图像的下载URL到表中显示 - Web Firebase Get Download URL of image from Storage to Display in Table 检索 Firebase 存储图像的下载 url 时出现问题 - Problem retrieving download url of Firebase storage image 如何获取Firebase存储下载URL的价值并将其存储在Firebase存储中…, - How to get the value of Firebase storage download url and store it in firebase storage…, 将图像从 URL 上传到 Firebase 存储 - Upload image from URL to Firebase Storage 在 React.js 中使用 Dropzone 时如何将图像上传到 Firebase 存储并获取图像的下载 URL - How to Upload Images to Firebase Storage and Get Image's Download URL's When Using Dropzone in React.js 将图像上传到 Firebase 存储后如何检索下载 Url,以便我可以将其保存到 Firebase 数据库? - How to retrieve the download Url after uploading image to Firebase storage, so that I can save it to Firebase database? 如何获取firebase文件存储的下载地址 - How to get the download Url of firebase file storage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM