9

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
  • You're using 'fetch' to mean 'upload'. The question would be much clearer if you were to make it clear that you mean 'upload' and not 'download'. Some of the answers assume you're asking about how to download. Commented Jul 10, 2014 at 17:36

2 Answers 2

12

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!

Sign up to request clarification or add additional context in comments.

2 Comments

But is it also possible to download picture from given url to have independent file on own server?
This creates an independent file on your own server. The only difference with a multipart form is that the data stream is coming from another source (e.g. url in this case). Paperclip's post processors will kick in and resize and save the images
1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.