将Url存储到Firebase -Xamarin中

时间:2017-07-04 15:44:47

标签: c# android xamarin xamarin.android

我可以将图像存储到数据库中。在我的图像表中,我想要网址本身,但是当我保存图像时,我得到这种网址(我不能告诉它是否是网址)看起来像"md59ff87d3098d3e76b10bcffd04c4d249f.Image@429ed2f8"但我想要的东西比如firebase.com/pet.jpg所以我可以把它叫回我的imageview。问题似乎出现在我的OnSuccess()中。我该怎么做呢?

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == PICK_IMAGE_REQUEST && resultCode == Result.Ok && data != null && data.Data != null)
            {

                uri = data.Data;

                try
                {

                    Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
                    imageViewDrop.SetImageBitmap(bitmap);

                }
                catch (FileNotFoundException e)
                {

                    e.StackTrace.ToString();
                }

                catch (IOException e)
                {
                    e.StackTrace.ToString();
                }

                if (uri != null)
                {
                    pd = new ProgressDialog(this);
                    pd.SetTitle("Uploading Profile Picture");
                    pd.Show();

                    StorageReference image = storageRef.Child(FB_STORAGE_PATH +System.DateTime.Today + "." + GetImageExt(uri));


                    image.PutFile(uri).AddOnSuccessListener(this).AddOnFailureListener(this);

                    image.PutFile(uri).AddOnProgressListener(this);




               }

            }
        }

        public string GetImageExt(Android.Net.Uri uri)
        {

            ContentResolver contentresolver = ContentResolver;
            MimeTypeMap mime = MimeTypeMap.Singleton;
            return mime.GetExtensionFromMimeType(contentresolver.GetType(uri));


        }

        public void OnSuccess(Java.Lang.Object result)
        {
            pd.Dismiss();

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

            ImageUpload uploads = new ImageUpload(uri.ToString());

            string uploadId = mDatabaseImage.Push().Key;
            mDatabaseImage.Child(user.Uid).Child(phId).Child(uploadId).SetValue(uploads.ToString());



        }

更新

  protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);



            if (requestCode == PICK_IMAGE_REQUEST && resultCode == Result.Ok && data != null && data.Data != null)
            {
                uri = data.Data;

                for (int i = 0; i < 5; i++){

                    pd = new ProgressDialog(this);
                    pd.SetTitle("Uploading Profile Picture");
                    pd.Show();
                    StorageReference oneRef = storageRef.Child("one " + i + "png.");
                    Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
                    MemoryStream stream = new MemoryStream();
                    bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
                    byte[] myData = stream.ToArray();

                    uploadTask = oneRef.PutBytes(myData);
                    uploadTask.AddOnSuccessListener(this);
                    uploadTask.AddOnFailureListener(this);
                }
        }

        public string GetImageExt(Android.Net.Uri uri)
        {

            ContentResolver contentresolver = ContentResolver;
            MimeTypeMap mime = MimeTypeMap.Singleton;
            return mime.GetExtensionFromMimeType(contentresolver.GetType(uri));


        }

        public void OnSuccess(Java.Lang.Object result)
        {
             pd.Dismiss();
            string uploadId = mDatabaseImage.Push().Key;
            var snapshot = result as SnapshotBase;
            var url = snapshot.Storage.Path;
            mDatabaseImage.Child(count.ToString()).Child(user.Uid).Child(phId).Child(uploadId).SetValue(new PeaceHeroImage(url).ToMap());

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();





        }

        public void OnFailure(Java.Lang.Exception e)
        {
            pd.Dismiss();

            Toast.MakeText(this, e.Message, ToastLength.Short).Show();

        }

2 个答案:

答案 0 :(得分:0)

  

但我想要像firebase.com/pet.jpg这样的东西,所以我可以把它叫回我的imageview。

从您的代码我认为您将图片上传到Firebase Storage,然后您可以将此图片的路径保存到Firebase Database,例如:

public class MyActivity : Activity, IOnSuccessListener, IOnFailureListener, IValueEventListener
{
    private DatabaseReference dbRef;
    private StorageReference imagesRef;
    private int count;

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

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

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

        FirebaseDatabase database = FirebaseDatabase.Instance;
        dbRef = database.GetReference("mygallery");

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

        Button btn = FindViewById<Button>(Resource.Id.createdb);
        btn.Click += Btn_Click;
    }

    private void Btn_Click(object sender, EventArgs e)
    {
        //upload to firebase storage
        for (int i = 0; i < 5; i++)
        {
            StorageReference oneRef = imagesRef.Child("one" + i + ".png");
            Bitmap bitmap = BitmapFactory.DecodeResource(this.Resources, Resource.Drawable.one);
            MemoryStream stream = new MemoryStream();
            bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
            byte[] data = stream.ToArray();

            UploadTask uploadtask = oneRef.PutBytes(data);
            uploadtask.AddOnSuccessListener(this);
            uploadtask.AddOnFailureListener(this);
        }
    }

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

    public void OnSuccess(Java.Lang.Object result)
    {
        Log.WriteLine(LogPriority.Debug, "storage", "success!");
        Toast.MakeText(this, "Success", ToastLength.Short);

        //retrieve url and name of uploaded image and insert to database
        var snapshot = result as SnapshotBase;
        var name = snapshot.Storage.Name;
        var uri = snapshot.Storage.Path;
        dbRef.Child(count.ToString()).Child("name").SetValue(name);
        dbRef.Child(count.ToString()).Child("imageurl").SetValue(uri);
        count++;
    }

    public void OnCancelled(DatabaseError error)
    {
        Log.WriteLine(LogPriority.Debug, "database", "Cancelled:" + error.ToString());
        Toast.MakeText(Application.Context, "Failed", ToastLength.Short);
    }

    public void OnDataChange(DataSnapshot snapshot)
    {
        Toast.MakeText(Application.Context, "Success", ToastLength.Short);
    }
}

以下是我的firebase存储和数据库的屏幕截图:

Storage

Database

答案 1 :(得分:0)

您必须将结果转换为UploadTask,以便像这样获取DownloadUrl

public void OnSuccess(Java.Lang.Object result)
        {
             pd.Dismiss();
            string uploadId = mDatabaseImage.Push().Key;
            var snapshot = result as SnapshotBase;
            string url = ((UploadTask.TaskSnapshot)result).DownloadUrl.ToString();
            mDatabaseImage.Child(count.ToString()).Child(user.Uid).Child(phId).Child(uploadId).SetValue(new PeaceHeroImage(url).ToMap());

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

        }