Paperclip直接通过url获取图像

gho*_*fle 9 ruby-on-rails paperclip

可以使用PaperClip通过URL获取图像吗?灵活成像是可能的,但fleximage不支持Rails3,所以我已经切换到回形针.

目前,我通过curl获取图像,将其保存在硬盘上并通过paperclip的image_file加载它.

我通过谷歌找不到真正的解决方案,所以希望你能帮助我.

Dan*_*urg 12

是的,这是可能的,非常简单.

在你的模型中:

#we use this to get the image.
require 'rest-open-uri'
Class Model << ActiveRecord::Base
has_attached_file :picture

#Get the picture from a given url.
def picture_from_url(url)
    self.picture = open(url)
end
Run Code Online (Sandbox Code Playgroud)

然后你可以做这样的事情:

#controller
@model.picture_from_url(<Your URL here>)
Run Code Online (Sandbox Code Playgroud)

因为我们用对象的其余部分保存了图像.您可以在视图中使用它:

<%= image_tag @model.picture.url %>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!


And*_*rew 1

<modelname>.<attachmentname>.url方法不符合您的要求吗?

换句话说,如果你的模型被称为Foo,并且你将其设置为has_attached_file :barthenfoo.bar.url应该给出你的图像的 url,你可以将其放入 animage_tag或 alink_to或任何你想要的内容中。

如果这不是您要找的东西,您能澄清一下您的意思吗?