个性化阅读
专注于IT技术分析

从Cloud Storage下载文件

在上一节中, 我们了解了上传文件的不同方法。现在, 我们将学习如何从Cloud Storage下载文件。为了下载文件, 首先, 我们必须创建要存储的文件的Cloud Storage引用。

从Cloud Storage下载文件

我们可以通过以下两种方式创建引用, 即通过将子路径附加到存储根以及从现有gs://或https:// URL引用云存储中的对象来创建引用。

// Creating a storage reference from our app
val storageRef = storage.reference

// Creating a reference with an initial file path and name
val pathReference = storageRef.child("images/stars.jpg")

// Creating a reference to a file from a Google Cloud Storage URI
val gsReference = storage.getReferenceFromUrl("gs://bucket/images/stars.jpg")

// Creating a reference from an HTTPS URL
// In the URL, characters are URL escaped!
val httpsReference = storage.getReferenceFromUrl(
        "https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg")

下载方式

创建适当的引用后, 我们调用各种方法来下载文件, 即getBytes(), getStream(), 或者我们可以使用getDownloadUrl()获取下载URL, 以通过另一个库下载文件。

从Cloud Storage下载文件

使用getBytes()方法是将文件下载到内存的最简单方法。如果我们请求的文件大于应用程序的可用内存, 则我们的应用程序将崩溃。 getBytes()需要下载的最大字节数。我们根据应用程序功能设置最大大小。

var jtpRef = storageRef.child("images/jtp.jpg")

val ONE_MEGABYTE: Long = 1024 * 1024
islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener {
    // Data for "images/jtp.jpg" is returned, use this as needed
}.addOnFailureListener {
    // Handling any errors
}

将数据下载到本地文件

如果要在脱机时访问文件或共享文件, 则可以使用getFile()方法。此方法将文件直接下载到本地设备。此方法返回一个DownloadTask, 我们可以使用它来管理下载并监视状态。

jtpRef = storageRef.child("images/jtp.jpg")

val localFile = File.createTempFile("images", "jpg")

jtpRef.getFile(localFile).addOnSuccessListener {
    // Local temp file has been created
}.addOnFailureListener {
    // Handling any errors
}

通过URL下载数据

如果我们已经具有基于URL的下载基础结构, 或者只是想共享一个URL, 则可以通过在存储上下文上调用getDownloadUrl()方法来获取文件的下载URL。

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

使用FirebaseUI下载图像

用于消除样板代码并推广Google最佳做法。 FirebaseUI提供了简单, 自定义和可用于生产环境的本机移动绑定。使用FirebaseUI, 我们可以通过与Glide的集成来快速, 轻松地从云存储中下载, 缓存和显示图像。

首先, 将FirebaseUI添加到我们的app / build.gradle中:

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

然后, 我们可以将图像直接从存储加载到ImageView中:

// Referencing to an image file in Cloud Storage
val storageReference = FirebaseStorage.getInstance().reference

// ImageView in our Activity
val imageView = findViewById<ImageView>(R.id.imageView)

// Downloading directly from StorageReference using Glide
Glide.with(this /* context */)
        .load(storageReference)
        .into(imageView)

赞(0)
未经允许不得转载:srcmini » 从Cloud Storage下载文件

评论 抢沙发

评论前必须登录!