Thursday, November 5, 2009

Send binary file as text

A time ago at a customer site, there were created all kinds of difficult solutions for sending binary files over http. As I'm not that smart and didn't get their solution, and I found it took to much effort to create this solution, I thought maybe I can use Groovy to create this functionality. Of course it worked ;-). Suppose you want a binary file being send as SOAP message. Here is a quick way of doing it.

Actual soap sending is not done as you can read. I'll update the post to achieve this later. For now the purpose of the blog is to show how easy you transform a binary file into text and back with Groovy.



// get a binary file
def filename = "c:\\governance-value-etc.pdf"

f = new File(filename)

base64Writable = f.readBytes().encodeBase64()

// we need a stringwriter
sw = new StringWriter()
writeableFile = new File("c:\\pdfAsBase64String.txt")
// because with a writer we can convert the Writeable to a String (result of encodeBase64 is a Writable)
String base64AsString = base64Writable.writeTo(sw).toString()
writeableFile.write(base64AsString)

// here we do the 'SOAP' sending.....
receivedSoapMessage = base64AsString

// this is our outputfile
// we need to get the DataOutputStream because...
dos = new File("C:\\copyOfPdf.pdf").newDataOutputStream()

bbytes = base64AsString.decodeBase64()

// ...we can throw in the whole byte array at once
dos.write(bbytes,0, bbytes.size())

// and voila, have file on 'the other side' per SOAP / other String message format
println 'done'

My first blog, be gentle ;-).

2 comments:

  1. That looks pretty sexy that SOAP sending stuff

    ReplyDelete
  2. You can also use withDataOutputStream(Closure) and write the bytes to the file. The closure will make sure the stream is closed properly.

    new File('c:/copyOpPdf.pdf').withDataOutputStream { dos ->
    dos.write bbytes, 0, bbytes.size()
    }

    ReplyDelete