当我尝试将图像上传到Firebase存储中时,putFile在kotlin中不起作用

时间:2019-07-17 17:19:36

标签: firebase kotlin firebase-storage

尝试将图像放入Firebase存储中,但似乎不起作用。

我试图更改规则并确保依赖项处于打开状态,并且还应用了所需的存储权限,但这似乎不起作用。

以下是用于验证用户并上传其个人资料图像的代码,验证有效,但上传无效。

var selectedPhotoUri: Uri? = null

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null && data.data != null) {
      // proceed and check what the selected image was....
      Log.d(TAG, "Photo was selected")

      selectedPhotoUri = data.data

      val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)

      selectphoto_imageview_register.setImageBitmap(bitmap)

      selectphoto_button_register.alpha = 0f
    }
  }

 private fun performRegister() {
    val email = email_edittext_register.text.toString()
    val password = password_edittext_register.text.toString()

    if (email.isEmpty() || password.isEmpty()) {
      Toast.makeText(this, "Please enter text in email/pw", Toast.LENGTH_SHORT).show()
      return
    }

    Log.d(TAG, "Attempting to create user with email: $email")

    // Firebase Authentication to create a user with email and password
    FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener {
          if (!it.isSuccessful) return@addOnCompleteListener

          // else if successful
          Log.d(TAG, "Successfully created user with uid: ${it.result!!.user.uid}")

          uploadImageToFirebaseStorage()
        }
        .addOnFailureListener{
          Log.d(TAG, "Failed to create user: ${it.message}")
          Toast.makeText(this, "Failed to create user: ${it.message}", Toast.LENGTH_SHORT).show()
        }
  }

 private fun uploadImageToFirebaseStorage() {
    if (selectedPhotoUri != null){

      val progressDialog = ProgressDialog(this)
      progressDialog.setTitle("Uploading...")
      progressDialog.show()

      val filename = UUID.randomUUID().toString()
      val ref = FirebaseStorage.getInstance().getReference("/images/$filename")
      Log.d(TAG, "this is the data $selectedPhotoUri")



      ref.putFile(selectedPhotoUri!!)
              .addOnSuccessListener {
                Log.d(TAG, "Successfully uploaded image: ${it.metadata?.path}")
                progressDialog.hide()
                ref.downloadUrl.addOnSuccessListener {
                  Log.d(TAG, "File Location: $it")

                  saveUserToFirebaseDatabase(it.toString())
                }
              }

              .addOnFailureListener {
                Log.d(TAG, "Failed to upload image to storage: ${it.message}")
              }

              .addOnProgressListener {taskSnapshot ->
                val progress = 100.0 * taskSnapshot.bytesTransferred/taskSnapshot.totalByteCount
                progressDialog.setMessage("Uploaded " +progress.toInt())

              }
    }

当我按下注册按钮时,剩下的就是进度对话框屏幕,但并没有结束。 performRegister函数在onCreate函数中执行。没有出现错误代码,我不确定是什么引起了该问题。存储规则是公开的,所以我也不认为这是问题所在。

1 个答案:

答案 0 :(得分:0)

refreference类型的对象。在Firebase文档中,它没有称为putFile()的方法。我认为是这种情况。如果要上传照片,可以使用put()代替putFile()selectedPhotoUri!!参数应为Blob或文件类型。

ref.put(selectedPhotoUri!!) //selectedPhotoUri blob or file
          .addOnSuccessListener {
            Log.d(TAG, "Successfully uploaded image: ${it.metadata?.path}")
            progressDialog.hide()
            ref.downloadUrl.addOnSuccessListener {
              Log.d(TAG, "File Location: $it")

              saveUserToFirebaseDatabase(it.toString())
            }
          }

more details