How to download an image file via HTTP into a temp file? - ruby

I've found good examples of NET::HTTP for downloading an image file, and I've found good examples of creating a temp file. But I don't see how I can use these libraries together. I.e., how would the creation of the temp file be worked into this code for downloading a binary file?
require 'net/http'
Net::HTTP.start("somedomain.net/") do |http|
resp = http.get("/flv/sample/sample.flv")
open("sample.flv", "wb") do |file|
file.write(resp.body)
end
end
puts "Done."

There are more api-friendly libraries than Net::HTTP, for example httparty:
require "httparty"
url = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/91/DahliaDahlstarSunsetPink.jpg/250px-DahliaDahlstarSunsetPink.jpg"
File.open("/tmp/my_file.jpg", "wb") do |f|
f.write HTTParty.get(url).body
end

require 'net/http'
require 'tempfile'
require 'uri'
def save_to_tempfile(url)
uri = URI.parse(url)
Net::HTTP.start(uri.host, uri.port) do |http|
resp = http.get(uri.path)
file = Tempfile.new('foo', Dir.tmpdir, 'wb+')
file.binmode
file.write(resp.body)
file.flush
file
end
end
tf = save_to_tempfile('http://a.fsdn.com/sd/topics/transportation_64.png')
tf # => #<File:/var/folders/sj/2d7czhyn0ql5n3_2tqryq3f00000gn/T/foo20130827-58194-7a9j19>

I like to use RestClient:
file = File.open("/tmp/image.jpg", 'wb' ) do |output|
output.write RestClient.get("http://image_url/file.jpg")
end

Though the answers above work totally fine, I thought I would mention that it is also possible to just use the good ol' curl command to download the file into a temporary location. This was the use case that I needed for myself. Here's a rough idea of the code:
# Set up the temp file:
file = Tempfile.new(['filename', '.jpeg'])
#Make the curl request:
url = "http://example.com/image.jpeg"
curlString = "curl --silent -X GET \"#{url}\" -o \"#{file.path}\""
curlRequest = `#{curlString}`

If you like to download a file using HTTParty you can use the following code.
resp = HTTParty.get("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png")
file = Tempfile.new
file.binmode
file.write(resp.body)
file.rewind
Further, if you want to store the file in ActiveStorage refer below code.
object.images.attach(io: file, filename: "Test.png")

Related

Post png image to pngcrush with Ruby

In ruby, I want to get the same result than the code below but without using curl:
curl_output = `curl -X POST -s --form "input=##{png_image_file};type=image/png" http://pngcrush.com/crush > #{compressed_png_file}`
I tried this:
#!/usr/bin/env ruby
require "net/http"
require "uri"
# Image to crush
png_image_path = "./media/images/foo.png"
# Crush with http://pngcrush.com/
png_compress_uri = URI.parse("http://pngcrush.com/crush")
png_image_data = File.read(png_image_path)
req = Net::HTTP.new(png_compress_uri.host, png_compress_uri.port)
headers = {"Content-Type" => "image/png" }
response = req.post(png_compress_uri.path, png_image_data, headers)
p response.body
# => "Input is empty, provide a PNG image."
The problem with your code is you do not send required parameter to the server ("input" for http://pngcrush.com/crush). This works for me:
require 'net/http'
require 'uri'
uri = URI.parse('http://pngcrush.com/crush')
form_data = [
['input', File.open('filename.png')]
]
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new uri
# prepare request parameters
request.set_form(form_data, 'multipart/form-data')
response = http.request(request)
# save crushed image
open('crushed.png', 'wb') do |file|
file.write(response.body)
end
But I suggest you to use RestClient. It encapsulates net/http with cool features like multipart form data and you need just a few lines of code to do the job:
require 'rest_client'
resp = RestClient.post('http://pngcrush.com/crush',
:input => File.new('filename.png'))
# save crushed image
open('crushed.png', 'wb') do |file|
file.write(resp)
end
Install it with gem install rest-client

Opening Remote Images to Use on GD2

Is there any way to "open" remote images to be used on GD2?
Open approach would be to download the image in tmp directory and then open it using gd2
Here how you download the file from remote location to tmp
require "rubygems"
### Method 1
require "net/http"
require "uri"
uri = URI.parse("image path")
http = Net::HTTP.new(uri.host, uri.port)
File.open("/tmp/a_#{Date.now}.png", "wb+") do |file|
file.write http.get(uri.path)
end
### Method 2
require "open-uri"
File.open("/tmp/a_#{Date.now}.png", "wb+") do |file|
file.write open("image path").read
end
Make sure the user has the permission to write in tmp directory

Is there an one line way to read-in remote CSV files using Ruby's Standard Library CSV, or must I use FasterCSV?

Neither CSV file method seems to work with a URI.
A Line at a Time:
CSV.foreach("path/to/file.csv") do |row|
# use row here...
end
All at Once
arr_of_arrs = CSV.read("path/to/file.csv")"
small change to Ashley's answer solved the similar question I had
require 'open-uri'
url = "http://somedata.com/file.csv"
csv_data = open(url)
csv_rows = CSV.parse(csv_data.read)
This seemed to work:
require 'open-uri'
url = "http://somedata.com/file.csv"
csv_data = open(url)
csv_rows = CSV.read(csv_data.path, { headers: true,
converters: :numeric,
header_converters: :symbol }
)
You might want to try RemoteTable:
t = RemoteTable.new("http://somedata.com/file.csv")
t.each do |row|
puts row['foo']
end
It can also read remote XLS, XLSX, Google Docs (spreadsheets), TSV, XML, HTML, etc. Lots of examples are in the README.

How do I download a file over HTTP using Ruby?

How do I download a file over HTTP using Ruby?
Probably the shortest way to download a file:
require 'open-uri'
download = open('http://example.com/download.pdf')
IO.copy_stream(download, '~/my_file.pdf')
require 'net/http'
#part of base library
Net::HTTP.start("your.webhost.com") { |http|
resp = http.get("/yourfile.xml")
open("yourfile.xml", "wb") { |file|
file.write(resp.body)
}
}
You can use open-uri, which is a one liner
require 'open-uri'
content = open('http://example.com').read
Simple...
response = Net::HTTP.get_response(URI.parse("yourURI"))
There are several ways, but the easiest is probably OpenURI. This blog post has some sample code, and also goes over Net::HTTP (with Hpricot) and Rio.

Calling a file from a website in Ruby

I'm trying to call resources (images, for example.) from my website to avoid constant updates. Thus far, I've tried just using this:
#sprite.bitmap = Bitmap.new("http://www.minscandboo.com/minscgame/001-Title01.jpg")
But, this just gives "File not found error". What is the correct method for achieving this?
Try using Net::HTTP to get a local file first:
require 'net/http'
Net::HTTP.start("minscandboo.com") { |http|
resp = http.get("/miscgame/001-Title01.jpg")
open("local-game-image.jpg", "wb") { |file|
file.write(resp.body)
}
}
# ...
#sprite.bitmap = Bitmap.new("local-game-image.jpg")

Resources