Tải tệp xuống bằng Cloud Storage trên Android

Cloud Storage for Firebase cho phép bạn nhanh chóng và dễ dàng tải xuống tệp từ một Cloud Storage nhóm do Firebase cung cấp và quản lý.

Tạo tệp đối chiếu

Để tải một tệp xuống, trước tiên hãy tạo một tệp đối chiếu Cloud Storagecho tệp mà bạn muốn tải xuống.

Bạn có thể tạo một tệp đối chiếu bằng cách thêm các đường dẫn con vào thư mục gốc của nhóm Cloud Storage hoặc tạo một tệp đối chiếu từ một URL gs:// hoặc https:// hiện có tham chiếu đến một đối tượng trong Cloud Storage.

Kotlin

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

Tải tệp xuống

Sau khi có tệp đối chiếu, bạn có thể tải tệp xuống từ Cloud Storage bằng cách gọi getBytes() hoặc getStream(). Nếu muốn tải tệp xuống bằng một thư viện khác, bạn có thể lấy URL tải xuống bằng getDownloadUrl().

Tải xuống trong bộ nhớ

Tải tệp xuống byte[] bằng phương thức getBytes(). Đây là cách dễ nhất để tải một tệp xuống, nhưng cách này phải tải toàn bộ nội dung của tệp vào bộ nhớ. Nếu bạn yêu cầu một tệp lớn hơn bộ nhớ có sẵn của ứng dụng, thì ứng dụng sẽ gặp sự cố. Để tránh các vấn đề về bộ nhớ, getBytes() sẽ lấy số byte tối đa để tải xuống. Đặt kích thước tối đa thành một giá trị mà bạn biết ứng dụng của mình có thể xử lý hoặc sử dụng một phương thức tải xuống khác.

Kotlin

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

Tải xuống một tệp cục bộ

Phương thức getFile() tải một tệp xuống trực tiếp thiết bị cục bộ. Hãy sử dụng phương thức này nếu người dùng muốn có quyền truy cập vào tệp khi ngoại tuyến hoặc chia sẻ tệp trong một ứng dụng khác. getFile() trả về một DownloadTask mà bạn có thể dùng để quản lý quá trình tải xuống và theo dõi trạng thái tải xuống.

Kotlin

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

Nếu bạn muốn chủ động quản lý quá trình tải xuống, hãy xem Quản lý quá trình tải xuống để biết thêm thông tin.

Tải dữ liệu xuống qua URL

Nếu đã có cơ sở hạ tầng tải xuống dựa trên URL hoặc chỉ muốn có một URL để chia sẻ, bạn có thể lấy URL tải xuống cho một tệp bằng cách gọi phương thức getDownloadUrl() trên một tệp đối chiếu Cloud Storage.

Kotlin

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

Tải hình ảnh xuống bằng FirebaseUI

FirebaseUI cung cấp các liên kết di động gốc đơn giản, có thể tuỳ chỉnh và sẵn sàng cho quá trình phát hành chính thức để loại bỏ mã nguyên mẫu và thúc đẩy các phương pháp hay nhất của Google. Khi sử dụng FirebaseUI, bạn có thể nhanh chóng và dễ dàng tải hình ảnh xuống, lưu vào bộ nhớ đệm và hiển thị hình ảnh từ Cloud Storage bằng cách tích hợp với Glide.

Trước tiên, hãy thêm FirebaseUI vào app/build.gradle:

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

Sau đó, bạn có thể tải hình ảnh trực tiếp từ Cloud Storage vào ImageView:

Kotlin

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

Xử lý các thay đổi về vòng đời hoạt động

Quá trình tải xuống tiếp tục diễn ra ở chế độ nền ngay cả sau khi có các thay đổi về vòng đời của activity (chẳng hạn như hiển thị hộp thoại hoặc xoay màn hình). Mọi trình nghe mà bạn đã đính kèm cũng sẽ vẫn được đính kèm. Điều này có thể gây ra kết quả không mong muốn nếu chúng được gọi sau khi hoạt động bị dừng.

Bạn có thể giải quyết vấn đề này bằng cách đăng ký trình nghe với phạm vi hoạt động để tự động huỷ đăng ký khi hoạt động dừng. Sau đó, hãy sử dụng phương thức getActiveDownloadTasks khi hoạt động khởi động lại để lấy các tác vụ tải xuống vẫn đang chạy hoặc đã hoàn tất gần đây.

Ví dụ bên dưới minh hoạ điều này và cũng cho thấy cách duy trì đường dẫn tham chiếu bộ nhớ đã sử dụng.

Kotlin

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!
                // ...
            }
        });
    }
}

Xử lý lỗi

Có một số lý do khiến lỗi có thể xảy ra khi tải xuống, bao gồm cả việc tệp không tồn tại hoặc người dùng không có quyền truy cập vào tệp mong muốn. Bạn có thể tìm thêm thông tin về lỗi trong phần Xử lý lỗi của tài liệu.

Ví dụ đầy đủ

Dưới đây là ví dụ đầy đủ về quá trình tải xuống có xử lý lỗi:

Kotlin

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

Bạn cũng có thể lấy và cập nhật siêu dữ liệu cho các tệp được lưu trữ trong Cloud Storage.