Banged my head against the wall a bit with this question a bit today: how to write binary output with ColdFusion?
The obvious choice would be to store the binary content in a file and use ColdFusion's cffile action = "readBinary"
tag.
However, there is this ominous note in
Macromedia's
documentation:
Note: This action reads the file into a variable in the local Variables scope. It is not intended for use with large files, such as logs, because they can bring down the server.
I could work around this by writing some custom Java code to read/generate the binary output. Which brought me to the next question: how do I get a suitable filehandle into my Java code?
After some searching around, the light dawned. ColdFusion MX runs in a servlet container (JRun), so there
must be a way to get at the servlet environment.
Indeed, there is an escape hatch: GetPageContext()
. The PageContext it
returns
seems quite similar to the JSP equivalent.
My proof-of-concept code ended up looking something like the following:
<cfobject action="create" type="java" class="bla.foo.JavaObject" name="javaObject"> <cfscript> context = getPageContext(); context.setFlushOutput(false); response = context.getResponse().getResponse(); out = response.getOutputStream(); javaObject.write(out); out.flush(); out.close(); </cfscript>
[ Late update: my example code now works properly
after I put getResponse()
in twice
as suggested in
Christian Cantrell's weblog entry on the subject.
]
[ Late update the second: in order to avoid the scary error message
Application server is busy. Either there are too many concurrent requests or the server still is starting up.
it helps to close the output. The example code is now much more close to the Cantrell version. ]