Convert %Stream.GlobalBinary to Base64
Hi community,
I'm calling to a API that it is retrieving the content of a file as Content of response. I'm catching the binary but I need to convert this Stream to a Base64 string.
I'm trying to convert a %Stream.GlobaBinary to a Base64 string using the following code, but it doesn't work.
do stream1.Rewind()
set response = ""
while 'stream1.AtEnd {
set temp=stream.Read(4000)
set temp=$system.Encryption.Base64Encode(temp)
set response = response_temp
}
ObjectScriptObjectScript
The content is not correctly converted to Base64
Also, I've tried to convert it as dynamic JSon and get the stream as base64
do stream1.Rewind()
set contentfile = {}
set contentfile.file = stream1
set response=contentfile.%Get("file",,"stream>base64")
ObjectScriptObjectScript
But the value of response is a %Stream.DynamicBinary
Is there any way to convert the content of the stream as Base64?
I'm sure that it must be very simple, but I don't found it :(
Best regards
You can use your second example above, then copy the content into a new %Stream.GlobalBinary:
Do strm.Rewind() Set o = {}, o.strm = strm, strm2 = o.%Get("strm",,"stream>base64") Set strm3 = ##class(%Stream.GlobalBinary).%New() Do strm3.CopyFrom(strm2)
But I need a string, not another GlobalBinary
When dealing with stream input, it’s good to keep in mind that strings are limited in length, as explained in the documentaton.
I think the 4000 character read from the unencoded source is the problem. That's not an "even number" for base64 encoding, meaning that the encoded version will have trailing "=" signs as padding, in this case 2 of them.
Changing to 3000 characters got it to work for me, meaning that the encoded chunks did not have trailing "=".
An easy test is to look at your final encoded text. If you see "=" chars anywhere except the end, this is your problem.
The trailing "=" is a problem because when you concatenate the encoded chunks those end up embedded in the result, making it invalid base64. You need to rig it so you don't get trailing "=" for any chunk except the last one. You do that by ensuring that your unconverted chunks have a number of bytes such that the bit count is divisible by 6.
Have you checked this comment?
https://community.intersystems.com/post/encoding-base64-stream-chunk-siz...
Thanks, using this code I've converted it to a Strem.GlobalChar and read the content correctly