I’ve seen a little bit of discussion on the Flexcoders mailing list recently regarding saving images created in a flex app to the server. Most of the solutions revolved around using HTTP to get the image from the flash player to the server. This had proved difficult for numerous reason. So I set out to try and find a simpler way. Now knowing that AMF is a binary protocol I figured it must be possible to send the binary image data to the server using Remoting.
And indeed it is. In fact it’s stunningly simple. The actual heavy lifting has already been done for us by Tinic Uro in his Image Encoding classes. All I had to do was capture the image data, encode it using Tinic’s classes and then send it to a ColdFusion CFC via remoting. I’ve put it up as a demo so you can see it in action.
The flex part is standard Remoting so you can look at the code in the download to see that part but the ColdFusion is shown below.
<cffunction name="upload" access="remote" returntype="string">
<cfargument name="ext" type="string" required="true">
<cfargument name="img" type="binary" required="true">
<cfset var name = "image" & dateFormat(now(), "yyyymmdd") &
timeFormat(now(), "HHmmss") & "." & arguments.ext>
<cffile action="write" file="#expandPath("..\images\#name#")#"
output="#img#" addnewline="false" >
<cfreturn "/images/#name#">
</cffunction>
As you can see the code required in ColdFusion to do a relatively complex task is minimal, it can all be boiled down to two things:
-
Setting the argument type of the image data to binary (I’m not even sure this is required).
-
Using the cffile tag to save that binary data to a file.
See I told you it was simple. Feel free to download the Image Upload Code and try it out for youself.