Scott Roth · Nov 18, 2016

Decode Base64 into a file

I am trying to come up with a way to decode the Base64 we receive in an HL7 message into a PDF file and save it in a directory on our AIX machine. I thought I had the following working at one time but I am having issues. Has anyone done this before?

ClassMethod DecodeBase64HL7ToFile(base64 As %Stream, Ancillary As %String) As %Boolean

set Oref = ##class(%FileBinaryStream).%New()
set Oref.Filename = Ancillary
Do base64.Rewind()

While 'base64.AtEnd {
    set ln=base64.ReadLine()
    set lnDecoded=$system.Encryption.Base64Decode(ln)
do Oref.Write(lnDecoded)

Do Oref.%Save()
quit 1



1 3,281
Discussion (5)1
Log in or sign up to continue

It is not so simple. Before decoding, you should strip any special characters, like line endings. Then you should read input stream in fixed size devisable by 4, and decode this value.

set stream1=##class(%Stream.GlobalBinary).%New()
set stream2=##class(%Stream.GlobalBinary).%New()

while 'base64.AtEnd {
    set temp=base64.Read()
    set temp=$translate(temp, $c(13,10))

    do stream1.Write(temp)

do stream1.Rewind()
while 'stream1.AtEnd {
    set temp=stream.Read(4000)
    set temp=$system.Encryption.Base64Decode(temp)

    do stream2.Write(temp)

It might be too late, but there is a GetFieldStreamBase64 method for exactly this purpose.

Thanks, the issue I am having though is that it will not even save the file I am writing to.  I am using GetFieldStreamRaw to get the Base64 into a tSC variable, so do I send that tSC variable to the function that I have created to get it to Decode and Save the file?

I figured out my issue. Thanks for your help.

Hi Dmitry

I used your code to convert a GlobalCharactarStream containing Base64 encoded file to a bytestream.

Thank you for your solution.