如何使用Kotlin将图像上传到Firebase

时间:2019-03-13 23:52:34

标签: android firebase kotlin firebase-storage

这是我必须要做的。我对于获取实例并以URI格式获取图片的引用感到困惑。

代码如下:

class MainActivity : AppCompatActivity(), View.OnClickListener {

    private val CAMERA_REQUEST_CODE = 12345
    private val REQUEST_GALLERY_CAMERA = 54654
    companion object {
        val TAG = "RegisterActivity"
    }
    val storage = FirebaseStorage.getInstance()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        scnbtn.setOnClickListener(this)
    }


    override fun onClick(v: View?) {
        when (v) {
            scnbtn -> {
                if (Build.VERSION.SDK_INT >= 23) {
                    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(
                            this,
                            arrayOf(android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_GALLERY_CAMERA)
                    } else {
                        openCamera()
                    }
                } else {
                    openCamera()
                }
            }
        }
    }

    private fun openCamera() {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (intent.resolveActivity(packageManager) != null)
            startActivityForResult(intent, CAMERA_REQUEST_CODE)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_GALLERY_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                openCamera()
                Log.d(TAG, "Button Pressed")
            } else {
                Toast.makeText(this@MainActivity, "Fail", Toast.LENGTH_SHORT).show()
            }
        }
    }

    var selectedPhotoUri: Uri? = null

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                CAMERA_REQUEST_CODE -> {

                    val extras = data?.getExtras()
                    val imageBitmap = extras?.get("data") as Bitmap
                    imagecap.setImageBitmap(imageBitmap)
                    val bytes = baos.toByteArray()

                    //FIREBASE



                    uploadImageToFirebaseStorage()

                    }

                }
            }
        }

    private fun uploadImageToFirebaseStorage() {

        if (imagecap == null) return

        val filename = "images/" + UUID.randomUUID().toString()
        val ref = storage.getReference(filename)

        ref.putFile(imagecap!!)
            .addOnSuccessListener {
                Log.d(TAG, "Successfully uploaded image: ${it.metadata?.path}")

                ref.downloadUrl.addOnSuccessListener {
                    Log.d(TAG, "File Location: $it")

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

}

代码可以正常工作,直到到达Firebase部分为止。我无法上载工作。它怎么知道Firebase存储在哪里?

3 个答案:

答案 0 :(得分:0)

请尝试使用此代码作为参考:

private fun getFileExtension(uri: Uri?): String? {
        val cR = activity!!.contentResolver
        val mime = MimeTypeMap.getSingleton()
        return mime.getExtensionFromMimeType(cR.getType(uri!!))
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            val selectedfile = data!!.data //The uri with the location of the file
            val fname = getFileName(selectedfile)
            val file = FileUtils.getFile(activity, selectedfile)

            val storage = FirebaseStorage.getInstance()
            val storageRef = storage.reference
            val progressDialog = ProgressDialog(getContext())
            progressDialog.setTitle("Uploading")
            progressDialog.show()
            val fileReference = mStorageRef!!.child(System.currentTimeMillis().toString()
                    + "." + getFileExtension(selectedfile))

            var bitmap: Bitmap? = null
            try {
                bitmap = MediaStore.Images.Media.getBitmap(activity!!.contentResolver, selectedfile)
            } catch (e: IOException) {
                e.printStackTrace()
            }

            val baos = ByteArrayOutputStream()
            bitmap!!.compress(Bitmap.CompressFormat.JPEG, 20, baos)
            val dat = baos.toByteArray()
            val uploadTask = fileReference.putBytes(dat)

            uploadTask.addOnFailureListener { exception -> Log.i("whatTheFuck:", exception.toString()) }.addOnSuccessListener {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                progressDialog.dismiss()
                Toasty.success(getContext()!!, "Image Uploaded", Toast.LENGTH_LONG, true).show()
                uploadTask.continueWithTask { task ->
                    if (!task.isSuccessful) {
                    }

                    fileReference.downloadUrl
                }.addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        val downloadUri = task.result

                        //DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAu.getInstance().getCurrentUser().getUid());
                        val url = downloadUri!!.toString()
                        Log.i("seeThisUri", downloadUri.toString())// This is the one you should store
                        db!!.collection(s!!).document(docname!!)
                                .update(
                                        "imageurl", url
                                )

                        //   Upload upload = new Upload(editTextName.getText().toString().trim(),

                        // Toast.makeText(getContext(),url,Toast.LENGTH_LONG).show();
                        //  String uploadId = ref.push().getKey();
                        //ref.child(uploadId).setValue(upload);


                    } else {
                        Toasty.info(getContext()!!, "Image Not Selected", Toast.LENGTH_LONG, true).show()
                    }
                }
            }.addOnProgressListener { taskSnapshot ->
                val progress = 100.0 * taskSnapshot.bytesTransferred / taskSnapshot.totalByteCount
                progressDialog.setMessage("Uploaded " + progress.toInt() + "%...")
            }


        } else if (requestCode == REQUEST_CAMERA && resultCode == Activity.RESULT_OK) {
            val extras = data!!.extras
            val selectedfile = extras!!.get("data") as Bitmap
            val imageuri = getImageUri(activity!!, selectedfile)
            val fname = getFileName(imageuri)
            val file = FileUtils.getFile(activity, imageuri)
            val storage = FirebaseStorage.getInstance()
            val storageRef = storage.reference
            val progressDialog = ProgressDialog(getContext())
            progressDialog.setTitle("Uploading")
            progressDialog.show()
            val fileReference = mStorageRef!!.child(System.currentTimeMillis().toString()
                    + "." + getFileExtension(imageuri))

            var bitmap: Bitmap? = null
            try {
                bitmap = MediaStore.Images.Media.getBitmap(activity!!.contentResolver, imageuri)
            } catch (e: IOException) {
                e.printStackTrace()
            }

            val baos = ByteArrayOutputStream()
            bitmap!!.compress(Bitmap.CompressFormat.JPEG, 20, baos)
            val dat = baos.toByteArray()
            val uploadTask = fileReference.putBytes(dat)

            uploadTask.addOnFailureListener { exception -> Log.i("whatTheFuck:", exception.toString()) }.addOnSuccessListener {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                progressDialog.dismiss()
                Toasty.success(getContext()!!, "Image Uploaded", Toast.LENGTH_LONG, true).show()
                uploadTask.continueWithTask { task ->
                    if (!task.isSuccessful) {
                    }

                    fileReference.downloadUrl
                }.addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        val downloadUri = task.result

                        //DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAu.getInstance().getCurrentUser().getUid());
                        val url = downloadUri!!.toString()
                        Log.i("seeThisUri", downloadUri.toString())// This is the one you should store
                        db!!.collection(s!!).document(docname!!)
                                .update(
                                        "imageurl", url
                                )

                        //   Upload upload = new Upload(editTextName.getText().toString().trim(),

                        // Toast.makeText(getContext(),url,Toast.LENGTH_LONG).show();
                        //  String uploadId = ref.push().getKey();
                        //ref.child(uploadId).setValue(upload);


                    } else {
                        Toasty.info(getContext()!!, "Image Not Selected", Toast.LENGTH_LONG, true).show()
                    }
                }
            }.addOnProgressListener { taskSnapshot ->
                val progress = 100.0 * taskSnapshot.bytesTransferred / taskSnapshot.totalByteCount
                progressDialog.setMessage("Uploaded " + progress.toInt() + "%...")
            }


        }
    }

    private fun getImageUri(context: Context, inImage: Bitmap): Uri {
        val bytes = ByteArrayOutputStream()
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
        val path = MediaStore.Images.Media.insertImage(context.contentResolver, inImage, "Title", null)
        return Uri.parse(path)
    }

    fun getFileName(uri: Uri?): String {
        var result: String? = null
        if (uri!!.scheme == "content") {
            val cursor = activity!!.contentResolver.query(uri, null, null, null, null)
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
                }
            } finally {
                cursor!!.close()
            }
        }
        if (result == null) {
            result = uri.path
            val cut = result!!.lastIndexOf('/')
            if (cut != -1) {
                result = result.substring(cut + 1)
            }
        }
        return result
    }

答案 1 :(得分:0)

要获取图像URi,请首先为uri创建一个全局的版本,例如“ var selectedphotouri:Uri?= null”,然后将其写在onActivityResult上,如下所示,在我的代码“ selectedphotouri = data.data”和uploadimageto中火力地堡写下面的代码

var selectedphotouri:Uri?=null // Golobal variable
 selectedphotouri=data.data   // write this in fun onActivityResult
  // write this in uploadimagefirebase function
   ref.putFile(selectimageuri!!).addOnCanceledListener {
         Log.d("main","Your photo is uploaded successfully")
         Toast.makeText(this,"upload image to firebase",Toast.LENGTH_LONG).show()

     }

答案 2 :(得分:0)

这对我有用。

  private fun addToStorage(){
    // get current user
    val user = auth.currentUser?.uid
    val ref = storage.reference.child(user.toString()).child(uri.lastPathSegment.toString())

    val uploadTask = ref.putFile(uri)
    val urlTask = uploadTask.continueWithTask { task ->
        if (!task.isSuccessful) {
            task.exception?.let {
                throw it
            }
        }
        ref.downloadUrl
    }.addOnCompleteListener { task ->
        if (task.isSuccessful) {
            val downloadUri = task.result
            Log.d(TAG, downloadUri.toString())
            // assign the link to companion object
            DOWNLOAD = downloadUri.toString()
            // load the firestore adding method
            addToFireStore()
        } else {
            // Handle failures
            // ...
        }
    }


}