Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Faraday Ruby gem to download image and write to disk

When using the Faraday gem to hit a URL for an image like this:

http_conn = Faraday.new do |builder|
  builder.adapter Faraday.default_adapter
end 
response = http_conn.get 'http://example.tld/image.png'

How can you write the image file from the Faraday response to disk?

Debugging the response.body attribute shows it is binary data.

Any help greatly appreciated.

like image 724
Eliot Sykes Avatar asked Oct 03 '11 18:10

Eliot Sykes


People also ask

How to download image in Ruby?

Plain old Ruby The most popular way to download a file without any dependencies is to use the standard library open-uri . open-uri extends Kernel#open so that it can open URIs as if they were files. We can use this to download an image and then save it as a file.

How do I read an image in Ruby?

You need to invoke mspaint.exe with the applicable command line flags. Do note though that I don't believe MSPaint handles JPG files. You'd need to search around google or perhaps submit another question regarding MSPaint and opening files via the command line.

What is Faraday Ruby?

Ruby Faraday is a simple, flexible HTTP client library, with support for multiple backends. Faraday also is a middleware. $ sudo gem install faraday. The module is installed with the sudo gem install faraday command.


1 Answers

Why not just write the response.body like any other file?

File.open('image.png', 'wb') { |fp| fp.write(response.body) }
like image 62
mu is too short Avatar answered Sep 21 '22 11:09

mu is too short