簡體   English   中英

在 Ionic 3 中從 Firebase 檢索照片

[英]Retrieving photos from Firebase in Ionic 3

我正在開發一個 Ionic 3 手機壁紙應用程序,我現在正在使用 Firebase 數據庫上傳照片我正在嘗試在應用程序中顯示這些照片

就像我上傳 3 張照片(1.jpg、2.jpg、3.jpg)一樣,我編寫了這段代碼來從數據庫中獲取它們。

 imageSource;
 photo;



 constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.imageSource = (1);
    this.getPhotoURL();
  }

  getPhotoURL() {
    firebase.storage().ref().child('/' + this.imageSource + '.jpg').getDownloadURL().then((url) => {
      this.photo = url;
    })
  }

在 HTML 中我有這個

<ion-col>
     <img src="{{photo}}">
</ion-col>

但是只能得到我寫的照片名稱.|| this.imageSource = (1);" ||. .|| this.imageSource = (1);" ||.每次我想獲得一張新照片時,我都必須創建一個新函數。

那么我怎樣才能為我上傳的任何照片獲得自動更新,或者我需要一個更好的代碼來為我提供 3 張照片並以一種簡單的方式檢索?

當你上傳文件時,你必須使用uploadTask.snapshot.downloadedURL獲取downloadURL並保存它,像這樣

public downloadedUrls: [];

var uploadTask = storageRef.child('images/rivers.jpg').put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){

  // Observe state change events such as progress, pause, and resume
  // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
  var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
  console.log('Upload is ' + progress + '% done');
  switch (snapshot.state) {
    case firebase.storage.TaskState.PAUSED: // or 'paused'
      console.log('Upload is paused');
      break;
    case firebase.storage.TaskState.RUNNING: // or 'running'
      console.log('Upload is running');
      break;
  }
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  this.downloadedUrls.push(uploadTask.snapshot.downloadURL);
});

例如,使用downloadedUR,您可以保存在一個數組中,然后,您可以使用保存圖像中的所有url在html中循環這個數組,如下所示:

<ion-col *ngFor="let photo of downloadedUrls">
   <img src="{{ photo }}">
</ion-col>

例如,其中downloadedUrls 可以是字符串數組。 我讓自己明白了嗎?

希望能幫助到你。

Ps:我從Firebase Storage Docs得到的上傳方法,你可以查看

https://firebase.google.com/docs/storage/web/upload-files?hl=pt-br

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM