Cloud Storage for Firebase 可讓你輕鬆快速地下載 檔案 (來源:Cloud Storage) 由 Firebase 提供並管理的值區
可建立參照
如要下載檔案,請先 建立 Cloud Storage 參照 加入要下載的檔案
您可以在
Cloud Storage 值區,或者從現有檔案建立參照
參照 Cloud Storage 中物件的 gs://
或 https://
網址。
Kotlin+KTX
// Create a storage reference from our app val storageRef = storage.reference // Create a reference with an initial file path and name val pathReference = storageRef.child("images/stars.jpg") // Create a reference to a file from a Google Cloud Storage URI val gsReference = storage.getReferenceFromUrl("gs://bucket/images/stars.jpg") // Create a reference from an HTTPS URL // Note that in the URL, characters are URL escaped! val httpsReference = storage.getReferenceFromUrl( "https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg", )
Java
// Create a storage reference from our app StorageReference storageRef = storage.getReference(); // Create a reference with an initial file path and name StorageReference pathReference = storageRef.child("images/stars.jpg"); // Create a reference to a file from a Google Cloud Storage URI StorageReference gsReference = storage.getReferenceFromUrl("gs://bucket/images/stars.jpg"); // Create a reference from an HTTPS URL // Note that in the URL, characters are URL escaped! StorageReference httpsReference = storage.getReferenceFromUrl("https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg");
下載檔案
有了參考資源後,你就能從「Cloud Storage」下載檔案
呼叫 getBytes()
或 getStream()
如果偏好下載檔案
但您可以使用 getDownloadUrl()
取得下載網址。
在記憶體中下載
使用 getBytes()
方法將檔案下載到 byte[]
。這是
下載檔案是最簡單的方法,但必須載入
將檔案匯入記憶體如果您要求的檔案超過應用程式可用空間
因此應用程式將當機為防範記憶體問題,getBytes()
需要的最大下載位元組數將大小上限設為其他內容
或其他下載方式。
Kotlin+KTX
var islandRef = storageRef.child("images/island.jpg") val ONE_MEGABYTE: Long = 1024 * 1024 islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener { // Data for "images/island.jpg" is returned, use this as needed }.addOnFailureListener { // Handle any errors }
Java
StorageReference islandRef = storageRef.child("images/island.jpg"); final long ONE_MEGABYTE = 1024 * 1024; islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() { @Override public void onSuccess(byte[] bytes) { // Data for "images/island.jpg" is returns, use this as needed } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } });
下載至本機檔案
getFile()
方法會將檔案直接下載到本機裝置。適用情況
使用者希望在離線時存取檔案,或是在
不同的應用程式getFile()
會傳回 DownloadTask
,供您用於管理
請依照下載狀態監控下載狀態,並監控下載狀態。
Kotlin+KTX
islandRef = storageRef.child("images/island.jpg") val localFile = File.createTempFile("images", "jpg") islandRef.getFile(localFile).addOnSuccessListener { // Local temp file has been created }.addOnFailureListener { // Handle any errors }
Java
islandRef = storageRef.child("images/island.jpg"); File localFile = File.createTempFile("images", "jpg"); islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { @Override public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) { // Local temp file has been created } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } });
如要主動管理下載項目,請參閱 詳情請參閱管理下載內容。
透過網址下載資料
如果您已擁有以網址為基礎的下載基礎架構,或是
要分享網址,您可以呼叫
Cloud Storage 參照的 getDownloadUrl()
方法。
Kotlin+KTX
storageRef.child("users/me/profile.png").downloadUrl.addOnSuccessListener { // Got the download URL for 'users/me/profile.png' }.addOnFailureListener { // Handle any errors }
Java
storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { // Got the download URL for 'users/me/profile.png' } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } });
使用 FirebaseUI 下載映像檔
FirebaseUI 相當簡單 且可用於實際工作環境的原生行動繫結 樣板程式碼並推廣 Google 最佳做法FirebaseUI 可讓您 輕鬆快速地下載、快取及顯示圖片 使用我們與以下項目整合:Cloud Storage 滑行。
首先,請將 FirebaseUI 新增至您的 app/build.gradle
:
dependencies { // FirebaseUI Storage only implementation 'com.firebaseui:firebase-ui-storage:7.2.0' }
然後您就可以直接從 Cloud Storage 將圖片載入 ImageView
:
Kotlin+KTX
// Reference to an image file in Cloud Storage val storageReference = Firebase.storage.reference // ImageView in your Activity val imageView = findViewById<ImageView>(R.id.imageView) // Download directly from StorageReference using Glide // (See MyAppGlideModule for Loader registration) Glide.with(context) .load(storageReference) .into(imageView)
Java
// Reference to an image file in Cloud Storage StorageReference storageReference = FirebaseStorage.getInstance().getReference(); // ImageView in your Activity ImageView imageView = findViewById(R.id.imageView); // Download directly from StorageReference using Glide // (See MyAppGlideModule for Loader registration) Glide.with(context) .load(storageReference) .into(imageView);
處理活動生命週期變更
即使活動生命週期有所變更 (例如 例如簡報或旋轉畫面)。你附加的所有事件監聽器 仍保持連結狀態這可能會導致未預期的結果 。
如要解決這個問題,可以利用活動範圍訂閱事件監聽器
,在活動停止時自動取消註冊。接著,使用
在活動重新啟動以取得下載時使用 getActiveDownloadTasks
方法
仍在執行或最近完成的工作
下例示範了這項做法,並示範如何保存儲存空間 參照路徑。
Kotlin+KTX
override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) // If there's a download in progress, save the reference so you can query it later outState.putString("reference", storageRef.toString()) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) // If there was a download in progress, get its reference and create a new StorageReference val stringRef = savedInstanceState.getString("reference") ?: return storageRef = Firebase.storage.getReferenceFromUrl(stringRef) // Find all DownloadTasks under this StorageReference (in this example, there should be one) val tasks = storageRef.activeDownloadTasks if (tasks.size > 0) { // Get the task monitoring the download val task = tasks[0] // Add new listeners to the task using an Activity scope task.addOnSuccessListener(this) { // Success! // ... } } }
Java
@Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // If there's a download in progress, save the reference so you can query it later if (mStorageRef != null) { outState.putString("reference", mStorageRef.toString()); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // If there was a download in progress, get its reference and create a new StorageReference final String stringRef = savedInstanceState.getString("reference"); if (stringRef == null) { return; } mStorageRef = FirebaseStorage.getInstance().getReferenceFromUrl(stringRef); // Find all DownloadTasks under this StorageReference (in this example, there should be one) List<FileDownloadTask> tasks = mStorageRef.getActiveDownloadTasks(); if (tasks.size() > 0) { // Get the task monitoring the download FileDownloadTask task = tasks.get(0); // Add new listeners to the task using an Activity scope task.addOnSuccessListener(this, new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { @Override public void onSuccess(FileDownloadTask.TaskSnapshot state) { // Success! // ... } }); } }
處理錯誤
下載時可能會發生錯誤的原因有很多,包括 檔案不存在,或使用者沒有存取所需檔案的權限。 如要進一步瞭解錯誤,請前往 處理錯誤 一節。
完整範例
下面是含有錯誤處理的下載完整範例:
Kotlin+KTX
storageRef.child("users/me/profile.png").getBytes(Long.MAX_VALUE).addOnSuccessListener { // Use the bytes to display the image }.addOnFailureListener { // Handle any errors }
Java
storageRef.child("users/me/profile.png").getBytes(Long.MAX_VALUE).addOnSuccessListener(new OnSuccessListener<byte[]>() { @Override public void onSuccess(byte[] bytes) { // Use the bytes to display the image } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } });
您也可以取得及更新中繼資料 針對儲存在 Cloud Storage 中的檔案