将 ByteArray 在 Kotlin 中转换为 Base64。

huangapple go评论138阅读模式
英文:

Convert ByteArray to Base64 in Kotlin

问题

我正在尝试在一个使用Kotlin编写的Spring项目中将ByteArray转换为Base64。我已经查看了现有的帖子,但它们没有帮助我。实际上,我正在尝试将blob转换为base64,但到目前为止我已经将blob转换为了byteArray,现在正在努力将byteArray转换为base64。这是我目前正在尝试的:

    var inByteArray = Base64.encodeBase64(blobAsBytes)         //inByteArray : ByteArray!
    var inByteArrayFormatted = Base64Utils.decode(inByteArray) //inByteArrayFormatted : ByteArray

我尝试了这个帖子中的方法:https://stackoverflow.com/questions/2418485/how-do-i-convert-a-byte-array-to-base64-in-java,但它们只是将字符串编码为Base64,而不是直接转换为Base64。我如何将一个byteArray转换为Base64?不是编码后的字符串,而是Base64?

感谢所有的帮助!
英文:

I am trying to convert a ByteArray to Base64 in a Spring project, written in Kotlin. I have checked existing posts but they didnt help me. Actually I am trying to convert a blob to base, but I converted the blob to byteArray so far and am struggling now to convert the bytearray to base64. This is what I am currently trying:

var inByteArray = Base64.encodeBase64(blobAsBytes)         //inByteArray : ByteArray!
var inByteArrayFormatted = Base64Utils.decode(inByteArray) //inByteArrayFormatted : ByteArray

I tried the things from this post https://stackoverflow.com/questions/2418485/how-do-i-convert-a-byte-array-to-base64-in-java, but they are just encoding strings but not directly to Base64. How can I convert a byte array to Base64? Not encoded strings but Base64?

Thanks for every help!

答案1

得分: 14

如果您正在将Kotlin与Java一起使用,您可以使用java.util.Base64ByteArray编码为String。我编写了一个扩展函数来实现这一点:

fun ByteArray.toBase64(): String = 
    String(Base64.getEncoder().encode(this))

// 使用:
val b64 = "asdf".toByteArray().toBase64()
// YXNkZg==


<details>
<summary>英文:</summary>

If you are using Kotlin with Java, you can use `java.util.Base64` to encode a `ByteArray` into a `String`. I wrote an extension function to do this:

    fun ByteArray.toBase64(): String = 
        String(Base64.getEncoder().encode(this))

    // Use:
    val b64 = &quot;asdf&quot;.toByteArray().toBase64()
    // YXNkZg==

</details>



# 答案2
**得分**: 0

val encodedUrl = Base64.getUrlEncoder().encodeToString(oriUrl.toByteArray())

<details>
<summary>英文:</summary>

    val encodedUrl = Base64.getUrlEncoder().encodeToString(oriUrl.toByteArray())


</details>



huangapple
  • 本文由 发表于 2020年10月23日 00:15:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64486317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定