Android Studio/ReviewMate

firebase에서 url로 이미지 저장하기[Kotlin]

kangchaewon 2023. 8. 30. 13:51
fun upLoadProfileImg(strImg : String) {
        // Firebase Storage의 파일 참조 가져오기
        val storageReference =
            FirebaseStorage.getInstance().getReference(strImg)
        Log.d(TAG, "해당 imageUrl${storageReference}")
// 파일의 다운로드 URL 가져오기
        storageReference.downloadUrl.addOnSuccessListener { uri ->
            val downloadUrl = uri.toString()
            Log.d(TAG, "해당 imageUrl${downloadUrl}")
            // 유저 프로필에 저장하기
            val userId = FirebaseAuth.getInstance().currentUser?.uid
            Log.d(TAG, "해당 아이디 ${userId}")
            Toast.makeText(context, "base${userId}", Toast.LENGTH_SHORT).show()
            if (userId != null) {
                val userDocumentRef =
                    FirebaseFirestore.getInstance().collection("users").document(userId)

                userDocumentRef.get()
                    .addOnSuccessListener { documentSnapshot ->
                        if (documentSnapshot.exists()) {
                            val user = documentSnapshot.toObject(UserModel::class.java)

                            if (user != null) {
                                // 이미지 URL을 사용하여 UserModel 업데이트
                                user.imageUrl = downloadUrl
                                // Firestore의 users 컬렉션 업데이트
                                userDocumentRef.set(user, SetOptions.merge())
                                    .addOnSuccessListener {
                                        Glide.with(requireContext())
                                            .load(downloadUrl)
                                            .into(binding.userProfile)  // yourImageView는 이미지를 표시할 ImageView입니다.

                                    }
                                    .addOnFailureListener { exception ->
                                        Log.e(TAG, "사용자 정보 업데이트 중 오류 발생: $exception")
                                    }
                            }
                        } else {
                            Log.d(TAG, "사용자 문서가 존재하지 않습니다.")
                        }
                    }
                    .addOnFailureListener { exception ->
                        Log.e(TAG, "사용자 데이터 가져오기 중 오류 발생: $exception")
                    }
            }


            Log.d(TAG, "다운로드 URL: $downloadUrl")
        }.addOnFailureListener { exception ->
            // 다운로드 URL을 가져오는 도중에 오류가 발생한 경우 처리
            Log.e(TAG, "다운로드 URL을 가져오는 중 오류 발생: $exception")
        }
    }

⇒ strImg : firebase에서 가져올 이미지 파일 (”패키지/이미지 파일.png”형식)

db : MyApplication에서 선언한 데이터베이스 전역변수

  1. strImg 이미지 파일 경로를 가져옴
  2. 파일의 uri경로 가져오기
storageReference.downloadUrl.addOnSuccessListener { uri ->
            val downloadUrl = uri.toString() ~~~~~~

 

3. 유저정보를 가져옴

 val userDocumentRef =
    FirebaseFirestore.getInstance().collection("users").document(userId) ~~~~~~~

4. 유저 모델의 imageUrl필드에 이미지 url저장

user.imageUrl = downloadUrl