Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

android - How to upload and store multiple images in Firebase?

In my project, I'm trying to upload multiple images to Firebase storage and storing the downloaded url of images to firebase database. Here is my code

suspend fun uploadData(dataMap: HashMap<String, String>, imagePaths: Array<Uri?>){
        withContext(Dispatchers.IO){
            dataMap["selfie"] =getUrlForGallery(imagePaths[0])
            dataMap["adhaar pic"] = getUrlForCamera(imagePaths[1])
                dbReference.collection("Users Data").document(firebaseAuth.currentUser?.uid!!)  // Not working properly
                    .set(dataMap).addOnCompleteListener {
                        uploadResponse.postValue("success")
                    }
        }
}

private suspend fun getUrlForGallery(imagePaths : Uri?) =
    suspendCoroutine<String> {continuation ->
        val reference =
            storageReference.reference.child("images/${firebaseAuth.currentUser?.uid}/")
                .child("gallery")
        reference.putFile(imagePaths!!)
            .addOnSuccessListener {

                reference.downloadUrl.addOnSuccessListener {

                    continuation.resume(it.toString())
                }
            }
    }

private suspend fun getUrlForCamera(imagePaths : Uri?) =
    suspendCoroutine<String> {continuation ->
        val reference =
            storageReference.reference.child("images/${firebaseAuth.currentUser?.uid}/")
                .child("camera")
        reference.putFile(imagePaths!!)
            .addOnSuccessListener {

                reference.downloadUrl.addOnSuccessListener {

                continuation.resume(it.toString())
                }
            }
    }

Edited : My Project level gradle is :-

  buildscript {
   ext.kotlin_version = "1.4.21"
    repositories {
    google()
    jcenter()
 }
 dependencies {
    def nav_version = "2.3.1"
    def koin_version = "2.1.5"
    classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'
    classpath "androidx.navigation:navigation-safe-args-gradle- plugin:$nav_version"
    classpath 'com.android.tools.build:gradle:4.1.1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'com.google.gms:google-services:4.3.4'
    classpath "org.koin:koin-gradle-plugin:$koin_version"
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
  repositories {
     google()
     jcenter()
     maven { url "https://oss.jfrog.org/libs-snapshot" }
     maven {
        url "https://maven.google.com"
     }
  }
 }

task clean(type: Delete) {
 delete rootProject.buildDir
 }

My App level gradle is :-

 apply plugin: 'com.android.application'
 apply plugin: 'kotlin-android'
 apply plugin: 'kotlin-android-extensions'
 apply plugin: 'kotlin-kapt'
 apply plugin: 'com.google.gms.google-services'
 apply plugin: "androidx.navigation.safeargs"
 apply plugin: 'koin'
 apply plugin: 'com.google.firebase.crashlytics'

 android {
  compileSdkVersion 29
  buildToolsVersion "30.0.1"

   defaultConfig {
    applicationId "com.sarim.zomato"
    minSdkVersion 21
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    vectorDrawables.useSupportLibrary = true
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        debuggable false
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
    debug {
        debuggable true
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
}
kotlinOptions {
    jvmTarget = "1.8"
}
buildFeatures{
    dataBinding = true
    viewBinding = true
}
}

dependencies {
def nav_version = "2.3.2"
def koin_version = "2.1.5"
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'


//Kotlin Coroutines
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.0"


//ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

//Material Design dependency
implementation 'com.google.android.material:material:1.3.0-beta01'

//Android Navigation Dependency
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"

//Koin
implementation "org.koin:koin-core:$koin_version"
implementation "org.koin:koin-androidx-scope:$koin_version"
implementation "org.koin:koin-androidx-viewmodel:$koin_version"

//firebase
implementation platform('com.google.firebase:firebase-bom:26.0.0')
implementation 'com.google.firebase:firebase-auth-ktx'
implementation 'com.google.firebase:firebase-storage'
implementation 'com.google.firebase:firebase-firestore-ktx'
implementation 'com.google.firebase:firebase-analytics:18.0.0'
implementation 'com.google.firebase:firebase-crashlytics:17.3.0'
implementation "androidx.browser:browser:1.3.0"

}

But it is not working. I also tried uploading images using for loop but that also was not behaving right way. How can i fix this problem? Please suggest me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try this

private lateinit var uid: String
suspend fun uploadData(dataMap: HashMap<String, String>, imagePaths: Array<Uri?>) {
    uid = Firebase.auth.currentUser!!.uid
    withContext(Dispatchers.IO) {
        dataMap["selfie"] = getUrl(imagePaths[0]!!, true)
        dataMap["adhaar pic"] = getUrl(imagePaths[1]!!, false)
        Firebase.firestore.document("Users Data/$uid").set(dataMap).await()
    }
}
private suspend fun getUrl(path: Uri, forGallery: Boolean): String {
    val fileName = if (forGallery) "gallery" else "camera"
    val ref = Firebase.storage.getReference("images/$uid/$fileName")
    ref.putFile(path).await()
    return ref.downloadUrl.await().toString()
}

then if that doesn't throw an exception the upload was successful

val uploadResponse = try {
    uploadData(...)
    "success"
} catch (e: Exception) {
    "failure"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...