What is the proper way to convert a byte [] to a Base64 string in Java? Better yet would be Grails / Groovy because it tells me that the encodeAsBase64()
functi
(adding this to this thread in the hopes that somebody else will get a hit on this and doesn't have to waste his valuable time)
I got stymied today when I tried to add in my Grails 2.3.11/Groovy 2.1.9 application the output of
String src = render(
model: ...,
template: ...,
)
.encodeAsBase64()
as a data-
attribute to a DOM element. But the atob()
in the corresponding JavaScript, i.e. the code that decodes the Base64 string from the data attribute, kept complaining about illegal characters, while other decoders, e.g. base64 -d
accepted the same Base64 string without problems.
The solution is to force the render()
return value to a single string and then apply the Base64 encoding, i.e.
String src = render(
model: ...,
template: ...,
)
.toString()
.encodeAsBase64()
or (if you consider encodeAsBase64()
as deprecated):
String src = render(
model: ...,
template: ...,
)
.toString()
.bytes
.encodeBase64() // add 'true' for chunked output