Cloud Storage for Firebase cho phép bạn nhanh chóng và dễ dàng tải tệp xuống từ một vùng lưu trữ Cloud Storage 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 tham chiếu Cloud Storage cho tệp mà bạn muốn tải xuống.
Bạn có thể tạo một tham chiếu bằng cách nối các đường dẫn con vào gốc của vùng chứa Cloud Storage hoặc bạn có thể tạo một 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
// 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ó một giá trị tham 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ể nhận URL tải xuống bằng getDownloadUrl()
.
Tải xuống trong bộ nhớ
Tải tệp xuống một 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ớ hiện có 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ố lượng 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 tệp cục bộ
Phương thức getFile()
tải một tệp xuống 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 truy cập vào tệp khi không có mạng hoặc chia sẻ tệp trong một ứng dụng khác. getFile()
sẽ 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 của quá trình 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ý nội dung tải xuống, hãy xem bài viết Quản lý nội dung 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 chia sẻ một URL, bạn có thể nhận 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 tham 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 gốc đơn giản, có thể tuỳ chỉnh và sẵn sàng cho sản xuất trên thiết bị di động để loại bỏ mã lặp lại 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ể 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 chế độ tích hợp của chúng tôi 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 một 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 trong vòng đời của Hoạt động
Quá trình tải xuống vẫn tiếp tục ở chế độ nền ngay cả sau khi vòng đời hoạt động thay đổi (chẳng hạn như khi trình bày một 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 dừng.
Bạn có thể giải quyết vấn đề này bằng cách đăng ký các trình nghe của mình bằng một phạm vi hoạt động để tự động huỷ đăng ký chúng 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 mới hoàn tất.
Ví dụ bên dưới minh hoạ điều này và cũng cho biết cách duy trì đường dẫn tham chiếu bộ nhớ đã 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ể xem thêm thông tin về các 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ề một lượt 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.