Xamarin.Android: 如何从 Firebase 存储下载文件?

Xamarin.Android: how to download file from Firebase Storage?

我将图像上传到 Firebase 存储的代码 (Xamarin.Android) 是

Android.Net.Uri filePath = data.Data;
StorageReference childRef = storageRef.Child("images/").Child(key);
Bitmap bitmap = Android.Net.MediaStore.Images.Media.GetBitmap(this.ContentResolver, filePath);
MemoryStream stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
byte[] bitmapData = stream.toArray();
UploadTask uploadTask = childRef.PutBytes(bitmapData);

而且有效!但是当我想下载文件时它不起作用...这是代码:

StorageReference childRef = storageRef.Child("images/").Child(childKey);
Android.Net.Uri uri = Android.Net.Uri.Parse(childRef.ToString());
imageView.setImageURI(uri);

有人知道为什么吗?我必须使用 childRef.DownloadURL 吗?但是如何(它returns一个Android.Gms.Tasks.Task)?谢谢!

根据您的代码 imageView.setImageURI(uri);,我猜您想要 download image to your memory

然后你可以像这样编写代码:

public class Activity1 : Activity, IOnSuccessListener, IOnFailureListener
{
    private FirebaseStorage storage;
    private ImageView imageview;
    private Task downloadtask;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your application here
        SetContentView(Resource.Layout.layout1);

        //auth
        FirebaseAuth mAuth = FirebaseAuth.Instance;
        FirebaseUser user = mAuth.CurrentUser;
        if (user == null)
        {
            var result = mAuth.SignInAnonymously();
        }

        storage = FirebaseStorage.Instance;
        //create child reference
        StorageReference storageRef = storage.Reference;
        StorageReference imagesRef = storageRef.Child("images");

        imageview = FindViewById<ImageView>(Resource.Id.imageview);    

        Button downloadimage = FindViewById<Button>(Resource.Id.downloadimage);
        downloadimage.Click += (sender, e) =>
        {
            //download image
            StorageReference testRef = imagesRef.Child("test.jpg");

            downloadtask = testRef.GetBytes(1200 * 800);
            downloadtask.AddOnSuccessListener(this);
            downloadtask.AddOnFailureListener(this);
        };
    }

    public void OnFailure(Java.Lang.Exception e)
    {
        Log.WriteLine(LogPriority.Debug, "storage", "Failed:" + e.ToString());
    }

    public void OnSuccess(Java.Lang.Object result)
    {
        Log.WriteLine(LogPriority.Debug, "storage", "success!");
        if (downloadtask != null)
        {
            var data = downloadtask.Result.ToArray<byte>();
            Bitmap bitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length);
            imageview.SetImageBitmap(bitmap);
            downloadtask = null;
        }
    }
}

Do I have to use the childRef.DownloadURL?

所以,没有"have to",解决Android.Gms.Tasks.Task问题的结果,你可以实现IOnSuccessListener接口,在OnSuccess事件中处理你的任务结果。