Google is committed to advancing racial equity for Black communities. See how.
本頁面由 Cloud Translation API 翻譯而成。
Switch to English

在Android上下載文件

借助Cloud Storage,開發人員可以從Firebase提供和管理的Google Cloud Storage存儲桶中快速輕鬆地下載文件。

創建參考

要下載文件,請首先為您要下載的文件創建Cloud Storage引用

您可以通過將子路徑追加到存儲根目錄來創建引用,也可以從現有gs://https:// URL引用引用,以引用Cloud Storage中的對象。

爪哇

// 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");

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")

下載文件

獲得參考後,您可以通過調用getBytes()getStream()從Cloud Storage下載文件。如果您希望使用其他庫下載文件,則可以使用getDownloadUrl()獲得下載URL。

內存下載

使用getBytes()方法將文件下載到byte[] 。這是下載文件的最簡單方法,但是必須將文件的全部內容加載到內存中。如果您請求的文件大於應用程序的可用內存,則應用程序將崩潰。為了防止出現內存問題, getBytes()佔用了最大的字節下載量。將最大大小設置為您知道應用程序可以處理的大小,或使用其他下載方法。

爪哇

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

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
}

下載到本地文件

getFile()方法直接將文件下載到本地設備。如果您的用戶希望脫機時可以訪問文件或在其他應用程序中共享文件,請使用此功能。 getFile()返回一個DownloadTask ,您可以使用它來管理下載並監視下載狀態。

爪哇

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

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
}

如果要主動管理下載,請參閱管理下載以獲取更多信息。

通過URL下載數據

如果您已經具有基於URL的下載基礎結構,或者只想共享一個URL,則可以通過在存儲引用上調用getDownloadUrl()方法來獲取文件的下載URL。

爪哇

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

Kotlin + KTX

storageRef.child("users/me/profile.png").downloadUrl.addOnSuccessListener {
    // Got the download URL for 'users/me/profile.png'
}.addOnFailureListener {
    // Handle any errors
}

使用FirebaseUI下載圖像

FirebaseUI提供簡單,可自定義且可用於生產環境的本機移動綁定,以消除樣板代碼並推廣Google最佳做法。使用FirebaseUI,您可以使用我們與Glide的集成快速輕鬆地從Cloud Storage下載,緩存和顯示圖像。

首先,將FirebaseUI添加到您的app/build.gradle

dependencies {
    // FirebaseUI Storage only
    implementation 'com.firebaseui:firebase-ui-storage:6.2.0'
}

然後,您可以將圖像直接從Storage加載到ImageView

爪哇

// 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(this /* context */)
        .load(storageReference)
        .into(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(this /* context */)
        .load(storageReference)
        .into(imageView)

處理活動生命週期更改

即使活動生命週期發生了變化(例如,顯示對話框或旋轉屏幕),下載也會在後台繼續進行。您已附加的所有監聽器也將保持附加狀態。如果在活動停止後調用它們,可能會導致意外結果。

您可以通過在活動範圍內訂閱偵聽器以在活動停止時自動註銷他們來解決此問題。然後,在活動重新啟動時使用getActiveDownloadTasks方法,以獲取仍在運行或最近完成的下載任務。

下面的示例演示了這一點,還顯示瞭如何持久使用所使用的存儲引用路徑。

爪哇

@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

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)

    // If there's a download in progress, save the reference so you can query it later
    storageRef?.let {
        outState.putString("reference", it.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

    tasks?.size?.let { it ->
        if (it > 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!
                // ...
            }
        }
    }
}

處理錯誤

導致下載錯誤的原因有很多,包括文件不存在或用戶無權訪問所需文件。有關錯誤的更多信息,請參見文檔的“ 處理錯誤”部分。

完整的例子

帶有錯誤處理的下載的完整示例如下所示:

爪哇

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

Kotlin + KTX

storageRef.child("users/me/profile.png").getBytes(Long.MAX_VALUE).addOnSuccessListener {
    // Use the bytes to display the image
}.addOnFailureListener {
    // Handle any errors
}

您還可以獲取和更新存儲在Cloud Storage中的文件的元數據