Quick Setup of Android Google Cloud Firebase Storage without background server

Google Cloud Firebase Storage is a good option if you are looking to store your files online without any background server and retrieve it later.
In this Tutorial, we are going to implement a very simple android demo app in which we will learn two things.

  1. How to upload the file to Google Cloud Firebase Storage.
  2. How to Download the file from Google Cloud Storage.

1.Project Setup for Firebase Storage

Create a Project with the name of Firebase Storage Demo in Android Studio.
Click on  Tool-Firebase.

Firebase Storage

Click on Storage.

Firebase Storage
  • Click on Upload and download a file with Firebase Storage.
  • Login to Firebase Console and add your app and follow the steps suggested.
  • Enter your project name same as it shows in your project.
  • Download the JSON file and store inside your app folder of the project.
Firebase Storage

Configure your project as given below and the below-given configuration as advice.

Project-level build.gradle (<project>/build.gradle):
buildscript {
  dependencies {
    // Add this line
    classpath 'com.google.gms:google-services:3.0.0'
  }
}
App-level build.gradle (<project>/<app-module>/build.gradle):
...
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'
includes Firebase Analytics by default help_outline

Finally, press “Sync now” in the bar that appears in the IDE.

Add the below dependency on your project build.gradle file and sync the project.

...
    compile 'com.google.firebase:firebase-auth:9.8.0'
    compile 'com.google.firebase:firebase-storage:9.8.0'

Now add required permission to AndroidMainfest.xml files.

...
  <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2. Layout File Configuration for Firebase Storage

Now add the button to upload and download the file to your main layout files.

...
 <TextView
        android:layout_width="wrap_content"
        android:textSize="16sp"
        android:layout_height="wrap_content"
        android:text="Hello Google Firebase Storage" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn_upload"
        android:text="Upload File"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn_download"
        android:text="Download File"/>

3.Method to Upload and Download the file from Firebase Storage

Create method to upload and download the file from Firebase Storage.

...
 public void uploadFile(){
        Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
        StorageReference riversRef = mStorageRef.child("images/myprofile.jpg");

        riversRef.putFile(file)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        // Get a URL to the uploaded content
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle unsuccessful uploads
                        // ...
                    }
                });
    } 

    public void downloadFile()  {
        File localFile = null;
        try {
            localFile = File.createTempFile("images", "jpg");
        } catch (IOException e) {
            e.printStackTrace();
        }
        StorageReference riversRef = mStorageRef.child("images/myprofile.jpg");
        riversRef.getFile(localFile)
                .addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                        // Successfully downloaded data to local file
                        // ...
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle failed download
                // ...
            }
        });
    }

Now add the on click listener to upload and download button to upload and download the file.

   mStorageRef = FirebaseStorage.getInstance().getReference();
        Button btn_upload= (Button) findViewById(R.id.btn_upload);
        Button btn_download= (Button) findViewById(R.id.btn_download);

        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                uploadFile();
            }
        });

        btn_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downloadFile();
            }
        });

4.Setting Firebase Rule

Now we are almost ready but we have done one more changes to Firebase google console so that our file is accessible publicly otherwise it will throw 403 error code. You need to implement some authentication method before publishing your app. Below is the different level of access rule in firebase console for file access.

// Anyone can read or write to the bucket, even non-users of your app.
// Because it is shared with Google App Engine, this will also make
// files uploaded via GAE public.
service firebase.storage {
  match /b/<your-firebase-storage-bucket>/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}
// Access to files through Firebase Storage is completely disallowed.
// Files may still be accessible through Google App Engine or GCS APIs.
service firebase.storage {
  match /b/<your-firebase-storage-bucket>/o {
    match /{allPaths=**} {
      allow read, write: if false;
    }
  }
}
// Only authenticated users can read or write to the bucket
service firebase.storage {
  match /b/<your-firebase-storage-bucket>/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}
// Grants a user access to a node matching their user ID
service firebase.storage {
  match /b/<your-firebase-storage-bucket>/o {
    // Files look like: "user/<UID>/path/to/file.txt"
    match /user/{userId}/{allPaths=**} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}

If have any query question in mind feel free to comment below.

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

Leave a Reply

Close Menu