Processing Remote Files with Attachment Fu
Bobby | Tuesday, November 27, 2007
I've used Rick Olson's attachment_fu on a few projects now, and it's become one of the first plugins I import into my rails directory. But for my current task I need to not only upload photos but also import external images from a data service and run them through the usual cropping and scaling. I think it is ideal for all images, regardless of source, to be run through the same model where they are subjected to the same operations and validations. So that's what we'll do.
Currently, when you post a multi-part form with a file input box named
This opens the attachment and places the contents in a TempFile just as if it had been uploaded. Keep in mind that while my input data is quite reliable, you may need to add a few checks to ensure you have a valid extension and mime type. You can use the new method thusly:
Bobby Uhlenbrock, Application Developer, Barefoot
Currently, when you post a multi-part form with a file input box named
uploaded_data
, attachment_fu will grab that TempFile with a setter of the same name and do its magic. I have followed the same process with a new method. It can go right in the model that has_attachment
:
# Takes input of a remote file via an absolute URL,
# reads it and passes it to attachment_fu for processing
def remote_data=(file_url)
return nil if file_url.nil?
open(file_url) do |data|
# extract the filename and extension from the url
temp_filename = URI.split(file_url)[5][/[^\/]+\Z/]
# pass details to attachment_fu
self.filename = temp_filename
self.temp_data = data.read
self.content_type = data.content_type
end
end
This opens the attachment and places the contents in a TempFile just as if it had been uploaded. Keep in mind that while my input data is quite reliable, you may need to add a few checks to ensure you have a valid extension and mime type. You can use the new method thusly:
photo = Photo.new
photo.remote_data = "http://www.somewhere.com/an_image.jpg"
photo.save
Bobby Uhlenbrock, Application Developer, Barefoot