Base64 encode Word document
Hello. I was asked to base64-encode files such as Word documents (which contain images) and then post them to a Jira server. I found code to base64 encode a file here:
https://community.intersystems.com/post/encoding-base64-stream-chunk-si…
It seemed to work, but when someone tried to open the Word document, the images inside could not be displayed.
Comments
Note: Base 64 encoding is not able to encode a string which contains unicode (2 byte) characters. If you need to Base 64 encode an unicode string, you should first translate the string to UTF8 format, then encode it. s BinaryText=$ZCONVERT(UnicodeText,"O","UTF8")
s Base64Encoded=$system.Encryption.Base64Encode(BinaryText)
Now to Decode it:
s BinaryText=$system.Encryption.Base64Decode(Base64Encoded)
s UnicodeText=$ZCONVERT(BinaryText,"I","UTF8")
The first part (Base 64 encoding is not able to encode ... unicode (2 byte) characters) is correct. The second part (data-->utf8-->base64 and base64-->utf8-->data) is correct only if there is an agreement beetwen the sender and receiver about the double-encoding (utf8+base64).
If I was told, I get a base64 encoded file then I expect a file which is only base64 encoded and not a mix of several encodings including base64. A simple way to encode your document could be something like this:
ClassMethod Encode(infile, outfile)
{
// file-binary reads bytes and not charactersset str = ##class(%Stream.FileBinary).%New()
set str.Filename = infile
set len = 24000// len #3 must be 0 !set nonl = 1// no-newline: do not insert CR+LFdo str.Rewind()
open outfile:"nwu":0if$test {
use outfile
while 'str.AtEnd { write$system.Encryption.Base64Encode(str.Read(len),nonl) }
close outfile
}
quit$test
}Thank you, Julius. I will give it a try...