Tải file bằng Cloud Storage trên Android

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

Tạo một tài liệu tham khảo

Để tải xuống tệp, trước tiên hãy tạo tham chiếu Cloud Storage cho tệp bạn muốn tải xuống.

Bạn có thể tạo tham 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 bạn có thể tạo tham chiếu từ URL gs:// hoặc https:// hiện có tham chiếu đến một đối tượng trong Cloud Storage.

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

Tải tập tin

Sau khi có tài liệu tham khảo, bạn có thể tải xuống tệp từ Cloud Storage bằng cách gọi getBytes() hoặc getStream() . Nếu bạn muốn tải xuống tệp bằng thư viện khác, bạn có thể nhận 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 nó phải tải toàn bộ nội dung tệp của bạn vào bộ nhớ. Nếu bạn yêu cầu tệp lớn hơn bộ nhớ khả dụng của ứng dụng, ứng dụng của bạn sẽ gặp sự cố. Để bảo vệ khỏi các vấn đề về bộ nhớ, getBytes() cần số byte tối đa để tải xuống. Đặt kích thước tối đa thành kích thước mà bạn biết ứng dụng của mình có thể xử lý hoặc sử dụng phương pháp tải xuống khác.

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

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

Phương thức getFile() tải tệp trực tiếp xuống thiết bị cục bộ. Sử dụng tùy chọn này nếu người dùng của bạn 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ề DownloadTask mà bạn có thể sử 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+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
    }
});

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

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

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

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

Tải xuống hình ảnh với FirebaseUI

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

Đầu tiên, thêm FirebaseUI vào app/build.gradle của bạn:

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

Sau đó, bạn có thể tải hình ảnh trực tiếp từ Cloud Storage vào 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);

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

Quá trình tải xuống tiếp tục ở chế độ nền ngay cả sau khi thay đổi vòng đời hoạt động (chẳng hạn như hiển thị hộp thoại hoặc xoay màn hình). Bất kỳ người nghe nào 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ý phạm vi hoạt động cho người nghe của mình để tự động hủy đăng ký họ khi hoạt động dừng lại. Sau đó, sử dụng phương thức getActiveDownloadTasks khi hoạt động khởi động lại để nhận các tác vụ tải xuống vẫn đang chạy hoặc đã hoàn thành gần đây.

Ví dụ dưới đây chứng minh điều này và cũng cho thấy cách duy trì đường dẫn tham chiếu lưu trữ được sử dụng.

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

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ả 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 đủ

Một ví dụ đầy đủ về việc tải xuống có xử lý lỗi được hiển thị bên dưới:

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

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.