Easy Upload via URL with attachment_fu

Allowing file uploads with attachment_fu is super easy, but I’ve found that users sometimes want to be able to “upload” a file directly from a URL. This saves them the steps of downloading the file, finding it on their computer, uploading it into your app, etc.

I did a bit of digging around before I came across this handy trick that makes it pretty painless to add uploading via a URL to your app. I’ve wrapped up the code a bit and added in a few niceties that I found necessary to avoid raising exceptions unnecessarily.

The best part is that you don’t need to change anything about your controller in order to get this to work. All you need is to add the uri attribute to your model and views, and you’re good to go.

# app/models/upload.rb

class Upload < ActiveRecord::Base
  
  # ...normal attachment_fu code (has_attachment, etc)...

  # allow uploads via URL
  require 'open-uri'
  attr_reader :url
  def url=(uri)
    return nil if uri.blank?
    io = (open(URI.parse(uri)) rescue return nil)
    (class << io; self; end;).class_eval do
      define_method(:original_filename) { base_uri.path.split('/').last }
    end
    self.uploaded_data = io
  end
end

# app/controllers/uploads_controller.rb

class UploadsController  :url_upload_not_found
  rescue_from Errno::ETIMEDOUT, :with => :url_upload_not_found
  rescue_from OpenURI::HTTPError, :with => :url_upload_not_found
  rescue_from Timeout::Error, :with => :url_upload_not_found

  def new
    @upload = Upload.new
  end

  def create
    @upload = current_user.uploads.build(params[:upload])
    if @upload.save
      redirect_to files_path
    else
      render :action => "new"
    end
  end

  def url_upload_not_found
    flash[:notice] = "Sorry, the URL you provided was not valid."
    redirect_to new_upload_path
  end
end

# app/views/uploads/new.html.erb


 { :multipart => true } do |f| -%>
  
   
   "Upload" %>

You can see a working example of all this in El Dorado. I was bored, so I decided to try my hand at making a screencast. Check it out – it’s got an awesome soundtrack at the very least🙂

http://vimeo.com/moogaloop.swf?clip_id=2060363&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1

If you’d like to use this for multiple models, consider refactoring it into a module that you can include elsewhere.

Hope this helps – and suggestions/improvements are always welcome!

Published by

Trevor Turk

A chess-playing machine of the late 18th century, promoted as an automaton but later proved a hoax.

13 thoughts on “Easy Upload via URL with attachment_fu”

  1. Hey,
    I was wondering how to get this to work with the resizing that attachment_fu can do? This method just uploads the image but doesn't take into account the resize_to or the thumbnails. Any suggestions?

  2. Thanks that works great!

    @Mark – It's creating thumbnails for me.. You may have a problem with RMagick or something?

Comments are closed.