Paperclip fetch image directly via url

你。 提交于 2019-11-29 18:32:21

问题


It's it possible to fetch an image via url using PaperClip ? It's possible with fleximage, but fleximage has no support for Rails3 so I've switched over to paperclip.

At present, I'm fetching the image via curl, saving it on the hdd and load it via image_file of paperclip.

I've found no real solution via google, so hopefully you can help me.


回答1:


Yes this is possible and amazingly simple.

In your model:

#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

And then you can do something like this:

#controller
@model.picture_from_url(<Your URL here>)

And because we saved the image with the rest of the object. You can just use this in your views:

<%= image_tag @model.picture.url %>

Hope this helps!




回答2:


Does the <modelname>.<attachmentname>.url method not do what you're looking for?

In other words, if your model is called Foo, and you set it to has_attached_file :bar then foo.bar.url should give the url of your image, which you can put into an image_tag or a link_to or whatever you want.

Could you clarify what you mean if that isn't what you're looking for?



来源:https://stackoverflow.com/questions/4830122/paperclip-fetch-image-directly-via-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!