How to get the file path from uri in Android devices having Oreo and above OS

前端 未结 3 1396
长发绾君心
长发绾君心 2021-01-16 21:34

To select an audio file using Intent , I am using this function :-

fun selectAudioFromStorage() {
    val pictureActionIntent = Intent(Intent.ACTION_GET_CONT         


        
3条回答
  •  离开以前
    2021-01-16 22:19

    I solved it. Simply call this getPathFromURI method and it will return the file path

    object RealPathHelper {
    
    private const val BUFFER_SIZE = 1024 * 2
    
    
    @TargetApi(Build.VERSION_CODES.O)
    fun getPathFromURI(
        context: Context,
        contentUri: Uri,
        fileNamePrefix: String,
        defaultFileExtension: String
    ): String? {
        val uriPath: String = contentUri.path ?: return null
        val fileName: String = MediaFileHelper.getFileNameWithExtension(uriPath)
    
        if (fileName.isNotBlank()) {
            val destFile =
                createOutputFile(context, contentUri, fileNamePrefix, defaultFileExtension)
            copyUriToFile(context, contentUri, destFile)
            return destFile.absolutePath
        }
        return null
    }
    
    private fun createOutputFile(
        context: Context,
        contentUri: Uri,
        fileNamePrefix: String,
        defaultFileExtension: String
    ): File {
        var count = 0
        var file: File
    
        val uriPath: String? = contentUri.path
        val fileExtension = if (uriPath == null) defaultFileExtension
        else MediaFileHelper.getFileExtension(uriPath)
    
        do {
            count++
    
            val mFileName = "$fileNamePrefix${StringHelper.getUniqueId()}$count$fileExtension"
            val newFilePath =
                "${context.getExternalFilesDir(null)?.absolutePath}${context.getString(R.string.audio_select_directory)}/$mFileName"
    
            file = File(newFilePath)
    
        } while (file.exists() && !file.isDirectory)
    
        return file
    }
    
    private fun copyUriToFile(context: Context, srcUri: Uri, dstFile: File) {
        try {
            val inputStream = context.contentResolver.openInputStream(srcUri) ?: return
            val outputStream = FileOutputStream(dstFile)
            inputStream.copyTo(outputStream, BUFFER_SIZE)
            inputStream.close()
            outputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    

提交回复
热议问题