Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save image from URL by paperclip

In Paperclip 3.1.4 it's become even simpler.

def picture_from_url(url)
  self.picture = URI.parse(url)
end

This is slightly better than open(url). Because with open(url) you're going to get "stringio.txt" as the filename. With the above you're going to get a proper name of the file based on the URL. i.e.

self.picture = URI.parse("http://something.com/blah/avatar.png")

self.picture_file_name    # => "avatar.png"
self.picture_content_type # => "image/png"

Here is a simple way:

require "open-uri"

class User < ActiveRecord::Base
  has_attached_file :picture

  def picture_from_url(url)
    self.picture = open(url)
  end
end

Then simply :

user.picture_from_url "http://www.google.com/images/logos/ps_logo2.png"

It didn't work for me until I used "open" for parsed URI. once I added "open" it worked!

def picture_from_url(url)
  self.picture = URI.parse(url).open
end

My paperclip version is 4.2.1

Before open it wouldn't detect the content type right, because it wasn't a file. It would say image_content_type: "binary/octet-stream", and even if I override it with the right content type it wouldn't work.


First download the image with the curb gem to a TempFile and then simply assign the tempfile object and save your model.


Into official documentation is reported here https://github.com/thoughtbot/paperclip/wiki/Attachment-downloaded-from-a-URL

Anyway it seems not updated, because in last version of paperclip something has changed and this line of code is no more valid:

user.picture = URI.parse(url)

It raise an error, in particular this error is raised:

Paperclip::AdapterRegistry::NoHandlerError: No handler found for #<URI:: ...

The new correct syntax is this one:

url = "https://www.example.com/photo.jpeg"
user.picture = Paperclip.io_adapters.for(URI.parse(url).to_s, { hash_digest: Digest::MD5 })

Also we need to add these lines into config/initializers/paperclip.rb file:

Paperclip::DataUriAdapter.register
Paperclip::HttpUrlProxyAdapter.register

Tested this with paperclip version 5.3.0 and it works.


It may helpful to you. Here is the code using paperclip and image present in remote URL .

require 'rubygems'
require 'open-uri'
require 'paperclip'
model.update_attribute(:photo,open(website_vehicle.image_url))

In model

class Model < ActiveRecord::Base
  has_attached_file :photo, :styles => { :small => "150x150>", :thumb => "75x75>" }
end