Cloud Storage cho Firebase giúp bạn tải xuống nhanh chóng và dễ dàng tệp từ Cloud Storage bộ chứa 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 tạo tệp đối chiếu trong Cloud Storage vào 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 đường dẫn con vào thư mục gốc của
bộ chứa Cloud Storage hoặc bạn có thể tạo tệp đối chiếu từ một tệp
URL gs://
hoặc https://
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ệp tải xuống
Sau khi có tệp đối chiếu, bạn có thể tải các tệp xuống từ Cloud Storage
bằng cách gọi getBytes()
hoặc getStream()
. Nếu bạn muốn tải tệp xuống
với 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 byte[]
bằng phương thức getBytes()
. Đây là
cách dễ nhất để tải tệp xuống, nhưng 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 tệp lớn hơn kích thước có sẵn của ứng dụng
thì ứng dụng của bạn sẽ gặp sự cố. Để tránh các vấn đề về bộ nhớ, hãy getBytes()
cần một số byte tối đa để tải xuống. Đặt kích thước tối đa thành một kích thước nào đó
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+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 tệp cục bộ
Phương thức getFile()
sẽ tải tệp trực tiếp xuống thiết bị cục bộ. Dùng cách 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 không có mạng hoặc muốn chia sẻ tệp trong
ứng dụng khác. getFile()
trả về một DownloadTask
mà bạn có thể dùng để quản lý
tải xuống của bạn 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, hãy xem Quản lý tài nguyên 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
một URL cần chia sẻ, bạn có thể lấy URL tải xuống của một tệp bằng cách gọi hàm
Phương thức getDownloadUrl()
trên một tệp tham chiếu trong 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 hình ảnh xuống bằng FirebaseUI
FirebaseUI cung cấp một số lợi ích đơn giản, các mối liên kết gốc có thể tuỳ chỉnh và sẵn sàng phát hành công khai để loại bỏ mã nguyên mẫu và quảng bá 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 một cách nhanh chóng và dễ dàng từ Cloud Storage bằng cách sử dụng công cụ tích hợp của chúng tôi với Lướt.
Trước tiên, hãy 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 về Vòng đời hoạt động
Quá trình tải xuống tiếp tục ở chế độ nền ngay cả khi vòng đời hoạt động thay đổi (chẳng hạn như như trình bày một hộp thoại hoặc xoay màn hình). Mọi trình nghe bạn đã đính kèm cũng sẽ được đính kèm. Việc này có thể dẫn đến kết quả không mong muốn nếu được gọi sau khi dừng hoạt động.
Bạn có thể giải quyết vấn đề này bằng cách đăng ký cho người nghe thông qua phạm vi hoạt động
để tự động huỷ đăng ký chúng khi hoạt động dừng lại. Sau đó, hãy sử dụng
Phương thức getActiveDownloadTasks
khi hoạt động khởi động lại để lấy tệp tải xuống
các công việc vẫn đang chạy hoặc mới hoàn thành gần đây.
Ví dụ bên dưới minh hoạ điều này cũng như cách duy trì bộ nhớ đường dẫn tham chiếu đã 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 tệp không tồn tại hoặc người dùng không có quyền truy cập tệp mong muốn. Bạn có thể xem thêm thông tin về các lỗi trong Xử lý lỗi của phần Tài liệu.
Ví dụ đầy đủ
Dưới đây là ví dụ đầy đủ về một tệp tải xuống có cách xử lý lỗ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ể tải và cập nhật siêu dữ liệu cho các tệp được lưu trữ trong Cloud Storage.