Utility Methods to Upload Images, Videos & Files to Firebase Storage in Java Android

The following are the utility methods that would help you to upload Images, Videos, Audios and all other types of files to Firebase Storage. This article also explains how to upload files into Firebase Storage.

If you are new to Firebase or Firebase Cloud Storage, you can read our Step by Step Guide to Integrate Firebase into your Project or Firebase Storage for Beginners. Following is the Java Solution for Android. You can also find here Kotlin or Swift solutions if you are looking for those.

Copy the below class FirebaseStorageManager.java into your project. In this class, you have 2 methods UploadBitmap & UploadFile. To upload bitmaps to Firebase Storage you can use UploadBitmap function. And to upload all kinds of files you can call UploadFile method.
You can call these methods from your Activity or Fragment by using following code.

1. To Upload Bitmap into Firebase Storage

FirebaseStorageManager.UploadBitmap(Your_Bitmap_Object, "fileName.png", new FirebaseStorageManager.UploadListener() {
    @Override
    public void onComplete(boolean isSuccess, String uploadedFileUrl) {
        Log.d("fileupload",isSuccess + "," + uploadedFileUrl);
    }
});

2. To Upload File into Firebase Storage

FirebaseStorageManager.UploadFile(Your_File_Object, "fileName.mp4", new FirebaseStorageManager.UploadListener() {
    @Override
    public void onComplete(boolean isSuccess, String uploadedFileUrl) {
        Log.d("fileupload",isSuccess + "," + uploadedFileUrl);
    }
});

FirebaseStorageManager.java Class

package com.example.testcodejava.utils;

import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;


public class FirebaseStorageManager {

    public interface UploadListener {
        void onComplete(boolean isSuccess, String uploadedFileUrl);
    }

    public static void UploadBitmap(Bitmap bitmap, String serverFileName, final UploadListener completionHandler) {

        if (bitmap == null) {
            completionHandler.onComplete(false,"");
        }
        FirebaseStorage storage = FirebaseStorage.getInstance();
        StorageReference storageRef = storage.getReference();
        // Create a reference to the file you want to upload
        String directory = "uploads/";
        final StorageReference fileRef = storageRef.child(directory + serverFileName);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] data = stream.toByteArray();

        UploadTask uploadTask = fileRef.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle unsuccessful uploads
                Log.e("oops","error in bitmap uploading");
                completionHandler.onComplete(false, "");
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            }
        });
        // Now we need to download url of uploaded file using a separate task
        Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (!task.isSuccessful()) {
                    throw task.getException();
                }
                // Continue with the task to get the download URL
                return fileRef.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    String stringUrl = downloadUri.toString();
                    completionHandler.onComplete(true, stringUrl);
                } else {
                    // Handle failures
                    completionHandler.onComplete(false, "");
                }
            }
        });
    }


    public static void UploadFile(File file, String serverFileName, final UploadListener completionHandler) {

                FirebaseStorage storage = FirebaseStorage.getInstance();
                StorageReference storageRef = storage.getReference();
                // Create a reference to the file you want to upload
                String directory = "uploads/";
                final StorageReference fileRef = storageRef.child(directory + serverFileName);

                try {
                        InputStream stream = new FileInputStream(file);
                        UploadTask uploadTask = fileRef.putStream(stream);
                        uploadTask.addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception exception) {
                                // Handle unsuccessful uploads
                                Log.e("oops","error in file uploading");
                                completionHandler.onComplete(false, "");
                                }
                            }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                }
                            });
                            // Now we need to download url of uploaded file using a separate task
                            Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                                @Override
                                public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                                    if (!task.isSuccessful()) {
                                        throw task.getException();
                                    }
                                    // Continue with the task to get the download URL
                                    return fileRef.getDownloadUrl();
                                }
                            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                                @Override
                                public void onComplete(@NonNull Task<Uri> task) {
                                    if (task.isSuccessful()) {
                                        Uri downloadUri = task.getResult();
                                        String stringUrl = downloadUri.toString();
                                        completionHandler.onComplete(true, stringUrl);
                                    } else {
                                        // Handle failures
                                        completionHandler.onComplete(false, "");
                                    }
                                }
                            });
                }catch (Exception e){
                    completionHandler.onComplete(false, "");
                }
    }

}

Note: This utility class will work only if your user is already authenticated to upload files to Firebase Storage, or the Security Rules are public. If it is not the case, please read about Firebase Storage Security Rules to run this solution successfully.

Thats it!! 🙂

You can also find other useful helping materials and tutorials in our Coding Articles & Tutorials Knowledge Base.

Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

4 thoughts on “Utility Methods to Upload Images, Videos & Files to Firebase Storage in Java Android

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.