Skip to content
This repository has been archived by the owner on Jul 13, 2023. It is now read-only.

Attachment downloaded from a URL

Mason Stewart edited this page Feb 4, 2018 · 6 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

For this to work, make sure that you've registered the URI adapter, which is not registered by default. Enable it by adding Paperclip::UriAdapter.register to config/initializers/paperclip.rb. Further details are in the IO Adapters section of the README.