Upload files to Android Firebase Stroage
1 min readJul 25, 2020
Hi guys,
How to upload a picture or other file to Firebase on Android and get the url of the file? Let’s start.
Add the dependency (app/build.gradle)
implementation 'com.google.firebase:firebase-storage-ktx:19.1.1'
Let’s add a storage reference.
val storageRef = Firebase.storage.reference
Now we need to define the directory where we will upload our file;
val myFileRef = storageRef.child("photos/<FILE_NAME>")
Let’s determine what type our file is.
val metadata = storageMetadata {
contentType = "image/jpeg"
}
Let’s upload our file to the directory we set in firebase stroage.
val uploadTask = myFileRef.putFile(fileUri,metadata)
We follow the installation process as follows: (If it worked for you, don’t forget to give a claps!)
uploadTask.addOnProgressListener { taskSnapshot ->
val progress = (100.0 * taskSnapshot.bytesTransferred) / taskSnapshot.totalByteCount
d { "Upload is $progress% done" }
}.addOnPausedListener {
d { "Upload is paused" }
}.addOnFailureListener {
d { "failure: ${it.printStackTrace()}" }
}.addOnSuccessListener {
profilePhotosRef.downloadUrl.addOnSuccessListener {
d { "downloadUrl: $it" }
}
}
As you can see, we can see all the stages of loading.
And when the upload is successful, we get the download url of this file.
It’s that simple.
All Simplecodes: