ดาวน์โหลดไฟล์ด้วย Cloud Storage บน Android

Cloud Storage for Firebase ช่วยให้คุณดาวน์โหลดได้อย่างรวดเร็วและง่ายดาย ไฟล์จาก Cloud Storage ระบุและจัดการโดย Firebase

สร้างการอ้างอิง

หากต้องการดาวน์โหลดไฟล์ ก่อนอื่นให้ สร้างข้อมูลอ้างอิง Cloud Storage ลงในไฟล์ที่คุณต้องการดาวน์โหลด

คุณสามารถสร้างข้อมูลอ้างอิงได้โดยต่อท้ายเส้นทางย่อยที่ราก ที่เก็บข้อมูล Cloud Storage หรือสร้างข้อมูลอ้างอิงจากที่เก็บข้อมูลที่มีอยู่ URL gs:// หรือ https:// กำลังอ้างอิงออบเจ็กต์ใน 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");

ดาวน์โหลดไฟล์

เมื่อมีข้อมูลอ้างอิงแล้ว คุณจะดาวน์โหลดไฟล์จาก Cloud Storage ได้ โดยโทรหา getBytes() หรือ getStream() หากต้องการดาวน์โหลดไฟล์ ด้วยไลบรารีอื่น คุณจะได้รับ URL สำหรับการดาวน์โหลดด้วย getDownloadUrl()

ดาวน์โหลดในหน่วยความจำ

ดาวน์โหลดไฟล์เป็น byte[] โดยใช้เมธอด getBytes() นี่คือ วิธีที่ง่ายที่สุดในการดาวน์โหลดไฟล์ แต่ต้องโหลดเนื้อหาทั้งหมดของ ไฟล์ของคุณลงในหน่วยความจำ หากคุณขอไฟล์ที่มีขนาดใหญ่กว่าที่แอปของคุณมีอยู่ แอปของคุณจะขัดข้อง getBytes()เพื่อป้องกันปัญหาเกี่ยวกับหน่วยความจำ ใช้จำนวนไบต์สูงสุดในการดาวน์โหลด ตั้งค่าขนาดสูงสุดเป็นอย่างอื่น ที่คุณทราบว่าแอปของคุณสามารถจัดการได้ หรือใช้วิธีดาวน์โหลดวิธีอื่น

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

ดาวน์โหลดไปยังไฟล์ในเครื่อง

เมธอด getFile() จะดาวน์โหลดไฟล์ลงในอุปกรณ์ในเครื่องโดยตรง ใช้ตัวเลือกนี้หาก ผู้ใช้ของคุณต้องมีสิทธิ์เข้าถึงไฟล์ขณะที่ออฟไลน์ หรือแชร์ไฟล์ใน แอปอื่น getFile() จะส่ง DownloadTask กลับมาซึ่งคุณใช้จัดการได้ การดาวน์โหลดของคุณ และตรวจสอบสถานะของการดาวน์โหลด

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

หากคุณต้องการจัดการการดาวน์โหลดด้วยตนเอง โปรดดู จัดการการดาวน์โหลดเพื่อดูข้อมูลเพิ่มเติม

ดาวน์โหลดข้อมูลผ่าน URL

ถ้าคุณมีโครงสร้างพื้นฐานในการดาวน์โหลดที่ใช้ URL อยู่แล้ว หรือเพียงต้องการ URL ที่จะแชร์ คุณสามารถรับ URL การดาวน์โหลดไฟล์ด้วยการเรียก getDownloadUrl() ในข้อมูลอ้างอิงของ 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
    }
});

การดาวน์โหลดรูปภาพด้วย Firebase UI

FirebaseUI นำเสนอ การเชื่อมโยงอุปกรณ์เคลื่อนที่ซึ่งกำหนดค่าได้และพร้อมใช้งานในเวอร์ชันที่ใช้งานจริงเพื่อกำจัด Boilerplate และโปรโมตแนวทางปฏิบัติแนะนำของ Google เมื่อใช้ FirebaseUI คุณสามารถ ดาวน์โหลด แคช และแสดงรูปภาพได้อย่างรวดเร็วและง่ายดาย จาก Cloud Storage โดยใช้การผสานรวมกับ แบบเลื่อนผ่าน

ขั้นแรก ให้เพิ่ม FirebaseUI ไปยัง app/build.gradle ดังนี้

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

จากนั้นคุณจะโหลดรูปภาพจาก Cloud Storage ไปยัง 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);

จัดการกับการเปลี่ยนแปลงวงจรของกิจกรรม

การดาวน์โหลดจะดำเนินการต่อไปในเบื้องหลัง แม้ว่าวงจรกิจกรรมจะเปลี่ยนแปลงไป (เช่น เป็นการนำเสนอกล่องโต้ตอบหรือหมุนหน้าจอ) ผู้ฟังที่คุณเคยแนบ จะยังแนบอยู่ ซึ่งอาจทำให้เกิดผลลัพธ์ที่ไม่คาดคิดหากได้รับ หลังจากหยุดกิจกรรมแล้ว

คุณแก้ปัญหานี้ได้โดยการสมัครรับข้อมูลผู้ฟังที่มีขอบเขตกิจกรรม เพื่อยกเลิกการลงทะเบียนโดยอัตโนมัติเมื่อกิจกรรมหยุดลง จากนั้นใช้ เมธอด getActiveDownloadTasks เมื่อกิจกรรมรีสตาร์ทเพื่อรับการดาวน์โหลด งานที่ยังดำเนินอยู่หรือเพิ่งทำเสร็จ

ตัวอย่างด้านล่างแสดงให้เห็นสิ่งนี้ และยังแสดงวิธีคงพื้นที่เก็บข้อมูล เส้นทางอ้างอิงที่ใช้

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

จัดการข้อผิดพลาด

มีหลายสาเหตุที่เกิดข้อผิดพลาดขณะดาวน์โหลด เช่น ไฟล์ที่ไม่มีอยู่ หรือผู้ใช้ไม่มีสิทธิ์เข้าถึงไฟล์ที่ต้องการ ดูข้อมูลเพิ่มเติมเกี่ยวกับข้อผิดพลาดได้ใน จัดการข้อผิดพลาด ของเอกสาร

ตัวอย่างแบบเต็ม

ตัวอย่างแบบเต็มของการดาวน์โหลดที่มีการจัดการข้อผิดพลาดแสดงอยู่ด้านล่าง

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

นอกจากนี้คุณยังรับและอัปเดตข้อมูลเมตาได้ด้วย สำหรับไฟล์ที่เก็บไว้ใน Cloud Storage