【问题标题】:Overwrite data in firebase database覆盖firebase数据库中的数据
【发布时间】:2020-09-28 10:55:03
【问题描述】:

我尝试创建一个存储空间,可以将我的图像保存在 firebase 存储空间中,但每次我上传新图像时,它都会替换旧图像,我希望每次都将新图像保存在存储空间中,我在 android studio 上使用kotlin,我的代码错了吗?这是我的代码


class Activity2 : AppCompatActivity() {

var curFile: Uri? = null
val imageRef = Firebase.storage.reference
private val userCollection = Firebase.firestore.collection("persons")

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity2)
    
    //here where a button to get an image from gallery
    tvpilihfoto.setOnClickListener {
        Intent(Intent.ACTION_GET_CONTENT).also {
            it.type = "image/*"
              val REQUEST_CODE_IMAGE_PICK = 0
                startActivityForResult(it, REQUEST_CODE_IMAGE_PICK)
         }
    //this button for an upload activity to send the image to database firebase
    btnupload.setOnClickListener {
        uploadImageToStorage("my image")
    }
}

private fun uploadImageToStorage(filename : String) = CoroutineScope(Dispatchers.IO).launch {
    try {
        curFile?.let {
             imageRef.child("images/$filename").putFile(it).await()
              withContext(Dispatchers.Main) {
                Toast.makeText(this@Activity2,"Foto anda telah dipilih",
                  Toast.LENGTH_LONG).show()
            }
        }
    } catch (e : Exception) {
        withContext(Dispatchers.Main) {
            Toast.makeText(this@Activity2,e.message,Toast.LENGTH_LONG).show()
        }
    }

}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    val REQUEST_CODE_IMAGE_PICK = 0
    if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGE_PICK) {
        data?.data?.let {
            curFile = it
            ivfoto.setImageURI(it) 
            //this where my image get or display in app
        }
    }
}
}

【问题讨论】:

  • 你确定你总是使用不同的名字吗?
  • 我尽量不要混淆,所以我使用我所有的布局来区分名称,我将通过使用 Kotlin 评论更清楚 //

标签: android firebase kotlin firebase-storage


【解决方案1】:

由于您始终调用uploadImageToStorage("my image"),因此图像将始终称为my image。因此,每次您进行该调用时,它都会覆盖存储中之前的 my image

要始终添加新图像,请在您的代码中生成唯一的文件名。例如:

uploadImageToStorage(UUID.randomUUID().toString())

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多