Another Way to Serve Binary Data

I made a post recently on using ColdFusion to write out binary data to the output stream in order to allow me to serve an image or other binary file that doesn’t exist on disk. The original code I posted looked like this:

<cffile action="readbinary" file="/home/cantrell/Pictures/Corrs2.jpg" variable="pic"/><cfscript>context = getPageContext();context.setFlushOutput(false);response = context.getResponse().getResponse();out = response.getOutputStream();response.setContentType("image/jpeg");response.setContentLength(arrayLen(pic));out.write(pic);out.flush();out.close();</cfscript>

In the example above, I’m reading the file from disk, but in a real-life situation, I would be getting the bytes from a URL or a database. Anyway, Spike Washburn (you guys know Spike?) was able to reduce the code above to just this:

<cffile action="readbinary" file="/home/cantrell/Pictures/Corrs2.jpg" variable="pic"/><cfcontent type="image/gif; charset=8859_1"><CFSCRIPT>writeOutput(toString(pic));</cfscript>

Very cool concept. (Hint: the key is in the character encoding.) Thanks for the fresh perspective, Spike!