Written by

Project Manager & Head of Interoperability at Salutic Soluciones, S.L.
Question Kurro Lopez · Apr 9, 2024

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
}

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")

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

Product version: IRIS 2021.1
$ZV: IRIS for Windows (x86-64) 2021.1.3 (Build 389U) Wed Feb 15 2023 14:50:06 EST

Comments

Brett Saviano · Apr 9, 2024

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)
0
Kurro Lopez  Apr 10, 2024 to Brett Saviano

But I need a string, not another GlobalBinary

0
Robert Barbiaux  Apr 10, 2024 to Kurro Lopez

When dealing with stream input, it’s good to keep in mind that strings are limited in length, as explained in the documentaton.

0
Clayton Lewis · Apr 9, 2024

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.

0
Kurro Lopez  Apr 10, 2024 to Luis Angel Pérez Ramos

Thanks, using this code I've converted it to a Strem.GlobalChar and read the content correctly

0