Thursday, April 15, 2010

Downloading files

Wow it's been a year since I've last posted!

I'm currently checking out dragonfly, the new kid on the block file processor. It's mean to replace stuff like paperclip and attachment_fu. To make things simple, especially if you don't have a lot of files, when migrating from either of those to dragonfly it may be simpler to just download the file and upload it again via dragonfly. This way you don't have to study the internals of each file management plugin.

So, here's how to download a file.

require 'net/http'

url = URI.parse "http://url.to/file.name"
Net::HTTP.start url.host do |http|
response = http.get url.path
MyModel.create! :file => response.body
# Here you tell your model to create the file.
# This is what the create action in the controller calls
# but instead of params[:file], you have response.body
end