How can I download a file from a URL and save it in Rails?


0

I have a URL to an image which i want to save locally, so that I can use Paperclip to produce a thumbnail for my application. What's the best way to download and save the image? (I looked into ruby file handling but did not come across anything.)


Share
asked 12 Aug 2022 06:10:18 PM
junaidakhtar

No comment found


Answers

0

Try this:

require 'open-uri'
open('image.png', 'wb') do |file|
  file << open('http://example.com/image.png').read
end

Share
answered 12 Aug 2022 06:10:47 PM
junaidakhtar

No comment found

0

An even shorter version:

require 'open-uri'
download = open('http://example.com/image.png')
IO.copy_stream(download, '~/image.png')

To keep the same filename:

IO.copy_stream(download, "~/#{download.base_uri.to_s.split('/')[-1]}")

Share
answered 12 Aug 2022 06:11:29 PM
junaidakhtar

No comment found

0

If you're using PaperClip, downloading from a URL is now handled automatically.

Assuming you've got something like:

class MyModel < ActiveRecord::Base
  has_attached_file :image, ...
end

On your model, just specify the image as a URL, something like this (written in deliberate longhand):

@my_model = MyModel.new
image_url = params[:image_url]
@my_model.image = URI.parse(image_url)

You'll probably want to put this in a method in your model. This will also work just fine on Heroku's temporary filesystem.

Paperclip will take it from there.

source: paperclip documentation


Share
answered 12 Aug 2022 06:12:11 PM
junaidakhtar

No comment found


You must log in or sign up to answer this question.