📌  相关文章
📜  Android:如何在 Firebase 存储上上传图像?

📅  最后修改于: 2022-05-13 01:55:05.081000             🧑  作者: Mango

Android:如何在 Firebase 存储上上传图像?

Firebase 是一个移动和 Web 应用程序开发平台。它提供 Web 应用程序或移动应用程序可能需要的服务。 Firebase 为 Firebase 应用程序提供安全的文件上传和下载。

本文介绍了如何构建一个能够从移动图库中选择图像并将图像上传到 Firebase 存储的 Android 应用程序。

以下是详细步骤:

  • 步骤 1.在 android studio 上创建一个新项目或打开一个现有项目,在其中添加身份验证并将 firebase 添加到该 android 应用程序。
  • 步骤 2.build.gradle (Module:app) 文件中添加 firebase 存储依赖项。 firebase 存储的最新依赖项是:
    implementation 'com.google.firebase:firebase-storage:19.1.0'
  • 步骤 3. 设置 activity_main.xml 布局文件
    activity_main.xml 布局文件包括:
    1. 两种布局:在相对布局中嵌套线性布局
    2. 两个按钮:
      • 用于从图库中选择图像的一种
      • 其他按钮用于将图像上传到云端的 Firebase 存储
    3. 显示从图库中选择的图像的图像视图

    以下是 activity_main.xml 的完整代码:

    activity_main.xml
    
    
      
     
     
      
        
        


    MainActivity.java
    package com.geeksforgeeks.uploadimagetofirebase;
      
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.net.Uri;
    import android.provider.MediaStore;
    import android.support.annotation.Nullable;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.Toast;
      
    import java.io.IOException;
    import java.util.UUID;
      
    public class MainActivity extends AppCompatActivity {
      
        // views for button
        private Button btnSelect, btnUpload;
      
        // view for image view
        private ImageView imageView;
      
        // Uri indicates, where the image will be picked from
        private Uri filePath;
      
        // request code
        private final int PICK_IMAGE_REQUEST = 22;
      
        // instance for firebase storage and StorageReference
        FirebaseStorage storage;
        StorageReference storageReference;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
      
            ActionBar actionBar;
            actionBar = getSupportActionBar();
            ColorDrawable colorDrawable
                = new ColorDrawable(
                    Color.parseColor("#0F9D58"));
            actionBar.setBackgroundDrawable(colorDrawable);
      
            // initialise views
            btnSelect = findViewById(R.id.btnChoose);
            btnUpload = findViewById(R.id.btnUpload);
            imageView = findViewById(R.id.imgView);
      
            // get the Firebase  storage reference
            storage = FirebaseStorage.getInstance();
            storageReference = storage.getReference();
      
            // on pressing btnSelect SelectImage() is called
            btnSelect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    SelectImage();
                }
            });
      
            // on pressing btnUpload uploadImage() is called
            btnUpload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    uploadImage();
                }
            });
        }
      
        // Select Image method
        private void SelectImage()
        {
      
            // Defining Implicit Intent to mobile gallery
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                Intent.createChooser(
                    intent,
                    "Select Image from here..."),
                PICK_IMAGE_REQUEST);
        }
      
        // Override onActivityResult method
        @Override
        protected void onActivityResult(int requestCode,
                                        int resultCode,
                                        Intent data)
        {
      
            super.onActivityResult(requestCode,
                                   resultCode,
                                   data);
      
            // checking request code and result code
            // if request code is PICK_IMAGE_REQUEST and
            // resultCode is RESULT_OK
            // then set image in the image view
            if (requestCode == PICK_IMAGE_REQUEST
                && resultCode == RESULT_OK
                && data != null
                && data.getData() != null) {
      
                // Get the Uri of data
                filePath = data.getData();
                try {
      
                    // Setting image on image view using Bitmap
                    Bitmap bitmap = MediaStore
                                        .Images
                                        .Media
                                        .getBitmap(
                                            getContentResolver(),
                                            filePath);
                    imageView.setImageBitmap(bitmap);
                }
      
                catch (IOException e) {
                    // Log the exception
                    e.printStackTrace();
                }
            }
        }
      
        // UploadImage method
        private void uploadImage()
        {
            if (filePath != null) {
      
                // Code for showing progressDialog while uploading
                ProgressDialog progressDialog
                    = new ProgressDialog(this);
                progressDialog.setTitle("Uploading...");
                progressDialog.show();
      
                // Defining the child of storageReference
                StorageReference ref
                    = storageReference
                          .child(
                              "images/"
                              + UUID.randomUUID().toString());
      
                // adding listeners on upload
                // or failure of image
                ref.putFile(filePath)
                    .addOnSuccessListener(
                        new OnSuccessListener() {
      
                            @Override
                            public void onSuccess(
                                UploadTask.TaskSnapshot taskSnapshot)
                            {
      
                                // Image uploaded successfully
                                // Dismiss dialog
                                progressDialog.dismiss();
                                Toast
                                    .makeText(MainActivity.this,
                                              "Image Uploaded!!",
                                              Toast.LENGTH_SHORT)
                                    .show();
                            }
                        })
      
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e)
                        {
      
                            // Error, Image not uploaded
                            progressDialog.dismiss();
                            Toast
                                .makeText(MainActivity.this,
                                          "Failed " + e.getMessage(),
                                          Toast.LENGTH_SHORT)
                                .show();
                        }
                    })
                    .addOnProgressListener(
                        new OnProgressListener() {
      
                            // Progress Listener for loading
                            // percentage on the dialog box
                            @Override
                            public void onProgress(
                                UploadTask.TaskSnapshot taskSnapshot)
                            {
                                double progress
                                    = (100.0
                                       * taskSnapshot.getBytesTransferred()
                                       / taskSnapshot.getTotalByteCount());
                                progressDialog.setMessage(
                                    "Uploaded "
                                    + (int)progress + "%");
                            }
                        });
            }
        }
    }


  • 步骤 4. 设置 MainActivity。Java
    在 MainActivity
    • 在定义的按钮视图的交互上设置侦听器。在交互时,您希望调用一个方法来触发从图库中选择图像或将所选图像上传到 Firebase 存储。 setOnClickListener用于交互操作。
    • 当调用 SelectImage 方法时,会创建一个新的 Intent 实例。意图类型设置为图像,其动作设置为获取一些内容。意图创建一个图像选择器对话框,允许用户搜索设备库以从库中选择图像。
    • startActivityForResult用于接收结果,即选中的图像。
    • 要显示此图像,请使用名为onActivityResult()的方法。 onActivityResult 接收请求代码、结果代码和数据。检查此方法,如果请求代码等于PICK_IMAGE_REQUEST ,结果代码等于RESULT_OK并且数据可用。如果这一切都属实,则在 ImageView 下面的按钮中显示所选图像。
    • 重写 startActivityForResult 方法并编写其实现。
    • 同样在uploadImage()方法中,获取 Firebase 存储引用,并使用putFile()函数将图像上传到具有成功和失败侦听器的 firebase 存储。如果上传了图像,则存在成功吐司,否则存在失败吐司。

    主要活动。Java

    package com.geeksforgeeks.uploadimagetofirebase;
      
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.net.Uri;
    import android.provider.MediaStore;
    import android.support.annotation.Nullable;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.Toast;
      
    import java.io.IOException;
    import java.util.UUID;
      
    public class MainActivity extends AppCompatActivity {
      
        // views for button
        private Button btnSelect, btnUpload;
      
        // view for image view
        private ImageView imageView;
      
        // Uri indicates, where the image will be picked from
        private Uri filePath;
      
        // request code
        private final int PICK_IMAGE_REQUEST = 22;
      
        // instance for firebase storage and StorageReference
        FirebaseStorage storage;
        StorageReference storageReference;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
      
            ActionBar actionBar;
            actionBar = getSupportActionBar();
            ColorDrawable colorDrawable
                = new ColorDrawable(
                    Color.parseColor("#0F9D58"));
            actionBar.setBackgroundDrawable(colorDrawable);
      
            // initialise views
            btnSelect = findViewById(R.id.btnChoose);
            btnUpload = findViewById(R.id.btnUpload);
            imageView = findViewById(R.id.imgView);
      
            // get the Firebase  storage reference
            storage = FirebaseStorage.getInstance();
            storageReference = storage.getReference();
      
            // on pressing btnSelect SelectImage() is called
            btnSelect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    SelectImage();
                }
            });
      
            // on pressing btnUpload uploadImage() is called
            btnUpload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    uploadImage();
                }
            });
        }
      
        // Select Image method
        private void SelectImage()
        {
      
            // Defining Implicit Intent to mobile gallery
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                Intent.createChooser(
                    intent,
                    "Select Image from here..."),
                PICK_IMAGE_REQUEST);
        }
      
        // Override onActivityResult method
        @Override
        protected void onActivityResult(int requestCode,
                                        int resultCode,
                                        Intent data)
        {
      
            super.onActivityResult(requestCode,
                                   resultCode,
                                   data);
      
            // checking request code and result code
            // if request code is PICK_IMAGE_REQUEST and
            // resultCode is RESULT_OK
            // then set image in the image view
            if (requestCode == PICK_IMAGE_REQUEST
                && resultCode == RESULT_OK
                && data != null
                && data.getData() != null) {
      
                // Get the Uri of data
                filePath = data.getData();
                try {
      
                    // Setting image on image view using Bitmap
                    Bitmap bitmap = MediaStore
                                        .Images
                                        .Media
                                        .getBitmap(
                                            getContentResolver(),
                                            filePath);
                    imageView.setImageBitmap(bitmap);
                }
      
                catch (IOException e) {
                    // Log the exception
                    e.printStackTrace();
                }
            }
        }
      
        // UploadImage method
        private void uploadImage()
        {
            if (filePath != null) {
      
                // Code for showing progressDialog while uploading
                ProgressDialog progressDialog
                    = new ProgressDialog(this);
                progressDialog.setTitle("Uploading...");
                progressDialog.show();
      
                // Defining the child of storageReference
                StorageReference ref
                    = storageReference
                          .child(
                              "images/"
                              + UUID.randomUUID().toString());
      
                // adding listeners on upload
                // or failure of image
                ref.putFile(filePath)
                    .addOnSuccessListener(
                        new OnSuccessListener() {
      
                            @Override
                            public void onSuccess(
                                UploadTask.TaskSnapshot taskSnapshot)
                            {
      
                                // Image uploaded successfully
                                // Dismiss dialog
                                progressDialog.dismiss();
                                Toast
                                    .makeText(MainActivity.this,
                                              "Image Uploaded!!",
                                              Toast.LENGTH_SHORT)
                                    .show();
                            }
                        })
      
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e)
                        {
      
                            // Error, Image not uploaded
                            progressDialog.dismiss();
                            Toast
                                .makeText(MainActivity.this,
                                          "Failed " + e.getMessage(),
                                          Toast.LENGTH_SHORT)
                                .show();
                        }
                    })
                    .addOnProgressListener(
                        new OnProgressListener() {
      
                            // Progress Listener for loading
                            // percentage on the dialog box
                            @Override
                            public void onProgress(
                                UploadTask.TaskSnapshot taskSnapshot)
                            {
                                double progress
                                    = (100.0
                                       * taskSnapshot.getBytesTransferred()
                                       / taskSnapshot.getTotalByteCount());
                                progressDialog.setMessage(
                                    "Uploaded "
                                    + (int)progress + "%");
                            }
                        });
            }
        }
    }
    

输出:

  • 主要活动

    主 Activity 包含用于选择和上传图像的按钮

  • 从图库中选择图像

    具有从图库中选择图像的图像视图的主要活动

  • firebase 控制台上上传的图片:
    注册用户

    注册用户