How to covert to pdf, doc, excel file which choose in application in base64 string I got this content://com.android.providers.media.documents/document/document%3A1000095307 but i can not convert base64 (pdf,doc,excel) in kotlin How to solved this please
I have one solution here that works for me
1. val contentUri = Uri.parse("url here of file path")
val fileContent = getContentFromFileUri(applicationContext, contentUri)
if (fileContent != null) {
havwPhoto = byteArrayToBase64(fileContent)
// Now you have the Base64 encoded string of the file content
} else {
// Handle the case where the content couldn't be read
}
2. fun getContentFromFileUri(context: Context, contentUri: Uri): ByteArray{
val contentResolver: ContentResolver = context.contentResolver
val inputStream: InputStream = contentResolver.openInputStream(contentUri)
val outputStream = ByteArrayOutputStream()
val buffer = ByteArray(1024)
var bytesRead: Int
try {
while (inputStream.read(buffer).also { bytesRead = it!! } != -1) {
outputStream.write(buffer, 0, bytesRead)
}
return outputStream.toByteArray()
} catch (e: Exception) {
e.printStackTrace()
} finally {
inputStream?.close()
outputStream.close()
}
return null
}
3. fun byteArrayToBase64(byteArray: ByteArray): String {
return Base64.encodeToString(byteArray, Base64.DEFAULT)
}