android - 从 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 构造函数的参数中?
解决方案
推荐阅读
- javascript - 在 ngb 轮播顶部滚动时无法滚动页面
- python - 是什么导致了 Symbolic pkg v2.9.0: 错误?
- javascript - 成功登录重定向后如何保留过滤器值
- function - 在小部件颤动中用作参数
- c - 如何正确链接 16 位和 32 位 .o 文件?
- java - 使用Apache spark java从列内容中提取特定字符串
- java - 使用 winium Java 实现桌面自动化
- java - 当 Java 发生 401 Unauthorized 错误时,如何捕获 POST 请求的 json 响应?
- node.js - 如何使用节点 js 在 dynamoDB 中为嵌套属性值编写过滤器表达式
- python-3.x - 我在 IDLE 中的 sys.path 与终端的 sys.path 不匹配。在哪里可以全局修改 Mac Big Sur 上的 python 路径?