attachment_fu For Image Streams

Just the other day, I was struggling with the problem that I needed to create an attachment from a base64 encoded image passed by a Flash object. My first idea was to encapsulate the data in an UploadedFile object, but I couldn’t get it to work without writing some pretty ugly code. I could also use the LocalFile model as described here, which you can use to pass a local file to attachment_fu. I figured that wouldn’t do the job properly either; you would write the data to the filesystem, pass the file, and attachment_fu would load it again.

Looking in the attachment_fu code, I found that it expects either a File or a StringIO. Moreover, it expects that it contains a original_filename method and a content_type method. My solution was therefore to create a small wrapper for the imagedata, which is based on StringIO:

# Usage example:
# model =
# model.uploaded_data =, filename, mime_type)
class VirtualImage < StringIO # Image mime types MIME_TYPES = [ "image/gif", "image/ief", "image/jpeg", "image/jpeg", "image/jpeg", "image/x-portable-bitmap", "image/x-portable-graymap", "image/png", "image/x-portable-anymap", "image/x-portable-pixmap", "image/cmu-raster", "image/x-rgb", "image/tiff", "image/tiff", "image/x-xbitmap", "image/x-xpixmap", "image/x-xwindowdump" ] # The filename of the image to be stored attr_reader :original_filename # The content type of the image_data attr_reader :content_type def initialize(image_data, filename, mime_type) raise "Unrecognized MIME type '#{mime_type}'" if !MIME_TYPES.include?(mime_type) @content_type = mime_type @original_filename = filename super(image_data) end end [/sourcecode] Of course, you can easily create a more general version to support any kind of data.

~ by moiristo on July 27, 2008.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: