首页 > 解决方案 > 从 Uri 获取文件导致 Kotlin 中的 FileNotFoundException,如何获取真实的文件路径

问题描述

我想通过 multipart 将画廊中挑选的徽标上传到我们的 api。我正在使用网络库中的 multipartFile 方法,在参数中获取一个文件:将文件上传到服务器

File 对象可以将 Uri 作为构造函数。

使用从图库返回的 uri,我可以在 ImageView 中显示图像,但是 uri 或 uri.path 在 FileConstructor 中传递时会导致 FileNotFoundException。(互联网、读、写权限在清单中声明)

有关于此功能的所有代码:

//selected image uri
private var imageUri: Uri? = null
set(value) {
    field = value

    field?.let { //value after picking image is : content://com.android.providers.media.documents/document/image%3A25
        uploadImageFile(imageUri= it,
            route = "uploadImageRoute/",
            onProgression = { progress ->
                Log.d("upload", "progress= $progress")
            },
            onSuccess = {
                Log.d("upload", "upload success !")
            },
            onError = { errorMessage ->
                Log.d("upload", "error= $errorMessage")
            })
        }
}


//select image button clicked, go to image gallery to pick an image
override fun onClick(v: View?) {
    val intent = Intent()
    intent.type = "image/*"
    intent.action = Intent.ACTION_GET_CONTENT
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0)
}


//comeback from image gallery
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null) {
        val selectedPhotoUri = data.data!!
        imageUri = selectedPhotoUri
    }
}

//prepare request headers
private fun configureHeaders(): MutableMap<String,Any> {
    var headerMap = mutableMapOf<String, Any>()
    headerMap["Content-Type"] = "multipart/form-data"
    headerMap["Accept"] = "application/json, text/plain"
    return headerMap
}

private fun uploadImageFile(imageUri: Uri, route: String, onProgression: (Double) -> Unit, onSuccess: () -> Unit, onError: (String?) -> Unit) {
    val headers = configureHeaders()
        var file = File(imageUri.path)

        AndroidNetworking.upload("https://api.ourDomain.com/$route")
            .addMultipartFile("file", file)
            .addHeaders(headers)
            .build()
            .setUploadProgressListener { uploaded, total ->
                val percentage = 100 * uploaded / total as Double
                onProgression(percentage)
            }
            .getAsJSONObject(object : JSONObjectRequestListener {
                override fun onResponse(response: JSONObject?) {
                    onSuccess()
                }

                override fun onError(anError: ANError?) {
                    onError(anError.toString())
                }
            })
}

如何获取文件的真实路径以放入 File 构造函数的参数中?

标签: androidfilekotlinuri

解决方案


推荐阅读