Skip to content

Attachment downloaded from a URL

Andrei Motinga edited this page Feb 6, 2016 · 5 revisions

There are times when you want the user to give you a URL to fetch an attachment from instead of physically uploading it in a multipart form. This is a common enough use case but there are many others which are similar. You need to fetch content from a URL and attach to paperclip. While this was fairly easy earlier, with paperclip (>= 3.1.4) it's become even easier.

Assuming you've already ran paperclip migration for your user model you can now

Model

class User < ActiveRecord::Base
  attr_reader :avatar_remote_url
  has_attached_file :avatar

  def avatar_remote_url=(url_value)
    self.avatar = URI.parse(url_value)
    # Assuming url_value is http://example.com/photos/face.png
    # avatar_file_name == "face.png"
    # avatar_content_type == "image/png"
    @avatar_remote_url = url_value
  end
end