Android Firebase File Storage - Part 1: Uploading Files

    In this blog, I had presented some Firebase features like account authentication, real-time database, put notifications. Because of being a major tool for providing quick back-end support for web pages and mobile applications now, Firebase has been added a lot of new features. Today, with this tutorial, I will introduce you to the file storage and retrieval functionality available for your Android apps.

Setting up Firebase to Android Studio project

    Firebase now has been integrated to Android Studio as a tool, so in the menu bar, let select Tool -> Firebase, you will see this panel on the right:
    Choose Storage entry and click "Upload and download file with Firebase Storage", this panel will appear:
    Choose "Connect to Firebase", Android Studio will launch your default browser and you must be logged in by Google account to continue, let follow these simple steps on Google developer console and when you return to Android Studio, you have this dialog:
    Choose an existed project on your Firebase console (or create a new project) and click "Connect to Firebase". After this process completed, click at "Add Firebase Storage to your app" (entry (2)), you'll have this dialog:
    Click "Accept Changes" to add these dependencies and google-services.json file to your project. You now have completed setting up environment work!
    As you can see at the right panel, at the entry (3), (4) and (5), these are tutorials about initializing StorageReference and download/upload files from/to Firebase Storage:

    Open Firebase console page and select your project, choose Storage in the left navigation column and select Rules tab, you'll see this code:
    In this tutorial, I would like to allow unauthenticated users to access and upload files to keep things simple. So on the line allow read, write: if request.auth != null;, change != to == and click the PUBLISH button:

    Now any user of your app should be able to upload or download files from your Firebase back-end. Please remember: this is not ideal for a production environment, but within the scope of a tutorial, it will make learning about Firebase Storage a lot easier without having to dig into authentication code.

Testing Upload/Download File on Firebase console

    Of course, you can manually upload files from the Firebase Console. Switch to tab File, you'll see a blue button titled Upload File:Click it and upload a file from your computer, it will appear in your Firebase Storage:
    Similar with upload, you can select a file from this page, "Download" button will appear and when click it, your file will be downloaded to your computer:

Upload a Byte array from Android application

    Now, turn to your Android project to write upload code. First of all, put an image (PNG) file to assets folder and a text file to raw folder like this:

    In order to access your Firebase Storage files, you'll need to first get a reference to the FirebaseStorage object, and then create a StorageReference to your project's URL and the file that you want to upload. You can find your project's URL at the top of the Files section of Storage in the Firebase Console. In onCreate() of your Activity, provide this code:
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageReference = storage.getReferenceFromUrl("gs://filestorage-d5afb.appspot.com").child("firebase.png");
    Next, we will need to get a byte array from the image file located in assets folder. We will retrieve it as a Bitmap, compressing it into a ByteArrayOutputStream, and then turning that into a byte[]. Then, you can create an UploadTask by calling putBytes(byte[]) to upload your image to Firebase. This UploadTask can also have an OnSuccessListener and OnFailureListener to handling the upload process result:
AssetManager assetManager = MainActivity.this.getAssets();
                InputStream istr;
                Bitmap bitmap;
                try {
                    //get bitmap from PNG file in assets folder
                    istr = assetManager.open("firebase.png");
                    bitmap = BitmapFactory.decodeStream(istr);

                    //decode to byte output stream
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                    byte[] data = outputStream.toByteArray();

                    //Upload to firebase
                    showProgressDialog("Upload Bitmap", "Uploading...");
                    UploadTask uploadTask = storageReference.putBytes(data);
                    uploadTask.addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            exception.printStackTrace();
                            dismissProgressDialog();
                            Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            dismissProgressDialog();
                            Toast.makeText(MainActivity.this, "Upload successful!", Toast.LENGTH_SHORT).show();
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
    In this sample project, upload process will be invoked after click a Button, this is output:
    Go to Firebase Console page, you will see the new uploaded file(firebase.png):

Uploading From an InputStream

    Now that you know how to upload a byte array, the other two types of uploads should be fairly intuitive. Let's say we have a text file named test.txt in our raw resources folder. We can read this into an InputStream and then upload it by using putStream(InputStream) method of StorageReference. Like the case above, we use an UploadTask to upload and adding addOnSuccessListener and addOnFailureListener to it:
                storageReference = storage.getReferenceFromUrl("gs://filestorage-d5afb.appspot.com").child("test_upload.txt");

                //Upload input stream to Firebase
                showProgressDialog("Upload File", "Uploading text file...");
                InputStream stream = getResources().openRawResource(R.raw.test);
                UploadTask uploadTask = storageReference.putStream(stream);
                uploadTask.addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        exception.printStackTrace();
                        dismissProgressDialog();
                        Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
                    }
                }).addOnSuccessListener(new OnSuccessListener() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        dismissProgressDialog();
                        Toast.makeText(MainActivity.this, "Upload successful!", Toast.LENGTH_SHORT).show();
                    }
                });
    And this is output of my sample project:
    Go to Firebase Console page, you will see new uploaded file named test_upload.txt:

    NOTE: You also have another upload option is File. Uploading an existing file is just as easy: simply get a reference to the file and call putFile(Uri) with a URI pointing to your file.

Conclusions

    In this post, I have presented the way to upload a file to Firebase. Based on the file type, we can upload it as a byte array or InputStream or File. Up to Part 2, I will talk about downloading file from Firebase Storage, coming soon!
    References:

Share


Previous post
« Prev Post
Next post
Next Post »