使用 kotlin for android app 将 pdf 文件上传到 firebase 存储

Posted

技术标签:

【中文标题】使用 kotlin for android app 将 pdf 文件上传到 firebase 存储【英文标题】:uploading pdf file to firebase storage using kotlin for android app 【发布时间】:2018-09-17 20:18:33 【问题描述】:

我正在开发一个使用 kotlin 将 pdf 文件上传到 firebase 存储的 android 应用程序 我遵循了一个教程,在运行时我只能浏览我的文件,但我无法选择要上传的任何文件这里是截图screenshot 这是来自 mainActivity.kt 的代码 在 MainActivity 类下:AppCompatActivity()

val pdf: Int=0
lateinit var uri:Uri
lateinit var mStorage: StorageReference

在 onCreate() 下

 val pdfBtn=findViewById<Button>(R.id.pdfBtn)
    mStorage=FirebaseStorage.getInstance().getReference("Uploads")

    pdfBtn.setOnClickListener(View.OnClickListener 
        view: View-> val intent = Intent()
        intent.setType("pdf/*")
        intent.setAction(Intent.ACTION_GET_CONTENT)
        startActivityForResult(Intent.createChooser(intent,"Select PDF"),pdf)
    )

其余与上传相关的方法

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) 
    val uriTxt=findViewById<TextView>(R.id.uriTxt)
    if(resultCode== Activity.RESULT_OK)
        if(requestCode==pdf)
            uri=data!!.data
            uriTxt.text=uri.toString()
            upload()

        
    

    super.onActivityResult(requestCode, resultCode, data)




private fun upload()
   var mRefrence= mStorage.child(uri.lastPathSegment)
   try
   mRefrence.putFile(uri).addOnSuccessListener 
       taskSnapshot: UploadTask.TaskSnapshot? -> var url =taskSnapshot!!.downloadUrl
       val dwnTxt=findViewById<TextView>(R.id.dwnTxt)
               dwnTxt.text=url.toString()
       Toast.makeText(this,"Successfully uploaded",Toast.LENGTH_LONG).show()
   
   
   catch (e: Exception)
       Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show()
   


请有人更正我的代码并告诉我它有什么问题。 非常感谢

【问题讨论】:

【参考方案1】:

如果有人想知道问题出在类型上

intent.setType("pdf/*")

修正是

intent.type="application/pdf"

【讨论】:

【参考方案2】:

我创建了这个实用程序类,以在协程的帮助下使用 kotlin 将多个图像上传到 firebase 存储。如果您有任何改进,请告诉我。

你需要先添加这些依赖。

实现 'com.google.firebase:firebase-storage-ktx:19.1.1'

//Firebase 通过 kotlinx-coroutines-play-services 库增加对 Coroutines 的支持

实现“org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.3.1”

更多信息请查看link、github link

private suspend fun uploadPhoto(file: File): Uri 
val storageRef = Firebase.storage.reference
        val fileName = UUID.randomUUID().toString()
        val fileUri = Uri.fromFile(file)

        return storageRef.child(fileName)
            .putFile(fileUri)
            .await()
            .storage
            .downloadUrl
            .await()
.
    

【讨论】:

以上是关于使用 kotlin for android app 将 pdf 文件上传到 firebase 存储的主要内容,如果未能解决你的问题,请参考以下文章

使用 Kotlin for Android 进行数据绑定的问题

Android 和 Web App 共享 Kotlin 代码

Kotlin for Android准备工作

使用Kotlin创建Android项目

Android开发-kotlin基本使用(一)

Kevin Learn Kotlin:构建第一个 Android App