试图在Android API的帮助下从内部存储中获取文件(PDF)以上传到服务器上ResultLauncher
,得到Uri,但我无法读取该Uri。当尝试在结果 Uri 的帮助下将该文件复制到我的应用程序的范围目录时,在contentResolver.openInputStream(uri)
. 这是错误:
Permission Denial: reading com.android.providers.media.MediaDocumentsProvider uri <my file uri> requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
如何在应用程序的范围目录中复制文件?这是我的 ResultLauncher:
singleTypeResultLauncher =
fragment.registerForActivityResult(ActivityResultContracts.GetContent()){
result ->
result?.let{
val tempUri = Uri.parse(it.toString().replace("%3A", ":"))
val path = createCopyAndReturnRealPath(fragment.requireContext(), tempUri)
}
}
这就是我的启动方式:
singleTypeResultLauncher.launch("application/pdf")
这是应用程序中的方法正在崩溃:
crashing on val inputStream = contentResolver.openInputStream(uri)
fun createCopyAndReturnRealPath(context: Context, uri: Uri): String? {
val contentResolver = context.contentResolver ?: return null
val mimeType = getMimeType(context, uri).getSafe()
val fileExt = "." + mimeType.substring(mimeType.indexOf('/') + 1)
val filePath: String = (context.dataDir.absolutePath + File.separator
+ System.currentTimeMillis())
val file = File(filePath)
try {
file.parentFile.mkdirs()
file.createNewFile()
val inputStream = contentResolver.openInputStream(uri) ?: return null //crashing here
val outputStream: OutputStream = FileOutputStream(file)
val buf = ByteArray(1024)
var len: Int
while (inputStream.read(buf).also { len = it } > 0) outputStream.write(buf, 0, len)
outputStream.close()
inputStream.close()
} catch (ignore: IOException) {
return null
}
return file.absolutePath
}
使用提供者路径:
<paths>
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>