Written by

Sr Application Development Analyst at The Ohio State University Wexner Medical Center
Question 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
}

Thanks

Scott

Comments

Dmitry Maslennikov · Nov 19, 2016

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)
}
0
Brendan Batchelder  Dec 2, 2016 to Scott Roth

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

0
Scott Roth  Nov 21, 2016 to Dmitry Maslennikov

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?

0
Scott Roth  Nov 21, 2016 to Dmitry Maslennikov

I figured out my issue. Thanks for your help.

0
Freek Felling  Jan 25, 2018 to Dmitry Maslennikov

Hi Dmitry

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

Thank you for your solution.

0