Guardar imagen desde URL por paperclip


Por favor, sugiéreme una forma de guardar una imagen desde una URL mediante Paperclip.

Author: smci, 2010-10-29

7 answers

Aquí hay una manera simple:

require "open-uri"

class User < ActiveRecord::Base
  has_attached_file :picture

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

Entonces simplemente:

user.picture_from_url "http://www.google.com/images/logos/ps_logo2.png"
 152
Author: Nicolas Blanco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-29 09:50:37

En Paperclip 3.1.4 se ha vuelto aún más simple.

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

Esto es ligeramente mejor que open(url). Porque con open (url) vas a obtener "stringio.txt " como el nombre del archivo. Con lo anterior vas a obtener un nombre propio del archivo basado en la URL. es decir,

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

self.picture_file_name    # => "avatar.png"
self.picture_content_type # => "image/png"
 192
Author: Aditya Sanghi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-06 15:43:38

Primero descargue la imagen con la gema curb a un TempFile y luego simplemente asigne el objeto tempfile y guarde su modelo.

 16
Author: Ariejan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-29 08:28:14

No funcionó para mí hasta que usé "open" para el URI analizado. una vez que agregué "abrir" funcionó!

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

Mi versión paperclip es 4.2.1

Antes de abrir no detectaba correctamente el tipo de contenido, porque no era un archivo. Diría image_content_type: "binary / octet-stream", e incluso si lo sobreescribo con el tipo de contenido correcto, no funcionaría.

 12
Author: Mïchael Makaröv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-21 20:06:27

Puede ser útil para usted. Aquí está el código que usa paperclip e imagen presente en la URL remota .

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

En el modelo

class Model < ActiveRecord::Base
  has_attached_file :photo, :styles => { :small => "150x150>", :thumb => "75x75>" }
end
 3
Author: prabu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-21 05:20:42

Como esas son respuestas antiguas, aquí hay una más nueva:

Agregue la URL remota de la imagen al Controlador deseado en la Base de datos

$ rails generate migration AddImageRemoteUrlToYour_Controller image_remote_url:string
$ rake db:migrate

Edita tu Modelo

attr_accessible :description, :image, :image_remote_url
.
.
.
def image_remote_url=(url_value)
  self.image = URI.parse(url_value) unless url_value.blank?
  super
end

*En Rails4 tienes que añadir el attr_accessible en el Controlador.

Actualiza tu formulario, si permites que otros suban una Imagen desde una URL

<%= f.input :image_remote_url, label: "Enter a URL" %>
 3
Author: The Mini John,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-26 18:57:17

Este es un método hardcore:

original_url = url.gsub(/\?.*$/, '')
filename = original_url.gsub(/^.*\//, '')
extension = File.extname(filename)

temp_images = Magick::Image.from_blob open(url).read
temp_images[0].write(url = "/tmp/#{Uuid.uuid}#{extension}")

self.file = File.open(url)

Donde Uuid.uuid sólo hace una identificación aleatoria.

 2
Author: Martin Streicher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-06 22:23:01