I share three examples Encoding as Base64 in Kotlin.
Example 1: from path.
import org.apache.commons.codec.binary.Base64
import org.apache.commons.io.FileUtils
import java.io.File
import java.nio.charset.StandardCharsets
fun main(args: Array<String>) {
val file = File("PATH_YOUR_FILE")
val encoded: ByteArray = Base64.encodeBase64(FileUtils.readFileToByteArray(file))
println("*****************************start ****************")
println(String(encoded, StandardCharsets.US_ASCII))
println("*****************************end *****************")
}
Example 2: from String
import org.apache.commons.codec.binary.Base64
import java.nio.charset.StandardCharsets
fun main(args: Array<String>) {
val encoded = Base64.encodeBase64("Test".toByteArray())
println("*****************************start ****************")
println(String(encoded, StandardCharsets.US_ASCII))
println("*****************************end *****************")
}
Example 3: from WS -> file: MultipartFile
import org.apache.commons.codec.binary.Base64
import org.springframework.web.multipart.MultipartFile
import java.nio.charset.StandardCharsets
fun encodeBase64(file: MultipartFile) {
val encoded: ByteArray = Base64.encodeBase64(file.bytes)
println("*****************************start ****************")
println(String(encoded, StandardCharsets.US_ASCII))
println("*****************************end *****************")
}