2017-06-14 53 views
1

我正在嘗試製作Ionic 2中的聊天應用程序。因此,當用戶在聊天內發送圖片時,我會將其上傳到Firebase存儲,併爲我提供一個網址該圖像。當用戶再次發送相同圖像時,圖像將再次上載到Firebase,並覆蓋之前的圖像,並提供一個新URL,導致舊圖像發送出現問題。Ionic 2應用程序:在Firebase存儲中上傳相同圖片

我知道顯而易見的解決方案是通過重命名來上傳圖片,但我不想多次上傳相同的圖片。有更聰明的解決方案嗎?請建議。

回答

1

您可以通過調用getDownloadUrl()來檢查文件是否已存在於Firebase存儲中。

ref.child('example.png').getDownloadURL() 
.then(url => { 
    // File exist 
}) 
.catch(err => { 
    // File didnt exist or other error 
}); 

編輯: 爲了防止兩個同名的不同圖像的上傳,我建議利用該customMetadata,對每個圖像與圖像的base64編碼MD5哈希標記。然後在上傳時使用此散列進行比較,當您遇到同名圖像時。如果它是不同的圖像具有相同的名稱,那麼你將不得不重新命名圖像。請務必重複此過程以處理具有相同名稱的2+圖像的情況。

一些僞代碼來說明我的意思:

uploadImg(img){ 
    hash = create base64 md5 hash of image 
    do { 
     if(filename exist in storage){ 
      get storage file metadata in order to get a hold of its hash 
      if(hash is equal to hash from storage){ 
       use file in storage instead 
      } 
      else{ 
       alter the filename eg. using a counter and make the do-while-loop run again 
     } 
     else{ 
      uploadFile(img, metadata containing hash) 
     } 
    }while(other file with same name exist in storage) 
} 
+0

感謝。不知道這存在。這在一定程度上有助於我的問題,但如果我上傳兩個具有相同名稱的不同圖像呢? –

相關問題