32 lines
977 B
Kotlin
32 lines
977 B
Kotlin
package core.utils
|
|
|
|
import android.content.Context
|
|
import android.net.Uri
|
|
import java.io.File
|
|
import java.io.FileOutputStream
|
|
import java.util.UUID
|
|
|
|
fun copyUriToFile(context: Context, uri: Uri): File? {
|
|
return try {
|
|
val cursor = context.contentResolver.query(uri, null, null, null, null)
|
|
val originalName = cursor?.use {
|
|
if (it.moveToFirst()) {
|
|
val index = it.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
|
|
if (index != -1) it.getString(index) else null
|
|
} else null
|
|
} ?: "${UUID.randomUUID()}.tmp"
|
|
|
|
val inputStream = context.contentResolver.openInputStream(uri)
|
|
val file = File(context.cacheDir, originalName)
|
|
val outputStream = FileOutputStream(file)
|
|
inputStream?.use { input ->
|
|
outputStream.use { output ->
|
|
input.copyTo(output)
|
|
}
|
|
}
|
|
file
|
|
} catch (e: Exception) {
|
|
null
|
|
}
|
|
}
|