Calling a file from a website in Ruby - 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")

Related

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

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")

Ruby File download

Is there a way of accessing this dialog box to get the file name or to save this file somewhere so i can access it later. I am using Ruby mechanize to navigate through the website to get to this screen.
There is no dialog with mechanize. You submit the form, that returns a Mechanize::File object, and you can then save that like so:
file = form.submit
File.open('myfile','w'){|f| f << file.body}
I would do it this way.
Use nokogiri to open the page:
#doc = Nokogiri::HTML(open(url))
go through the doc page and find that link for download.
then you can use something link this:
require 'net/http'
Net::HTTP.start('theserver.com') { |http|
resp = http.get('/xx/the_file_to_downlaod.csv')
open('the_downlaod.csv', 'wb') { |file|
file.write(resp.body)
}
}

Using Ruby, what is the most efficient way to get the content type of a given URL?

What is the most efficient way to get the content-type of a given URL using Ruby?
This is what I'd do if I want simple code:
require 'open-uri'
str = open('http://example.com')
str.content_type #=> "text/html"
The big advantage is it follows redirects.
If you're checking a bunch of URLs you might want to call close on the handles after you've found what you want.
Take a look at the Net::HTTP library.
require 'net/http'
response = nil
uri, path = 'google.com', '/'
Net::HTTP.start(uri, 80) { |http| response = http.head(path) }
p response['content-type']

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.

Download image with Ruby RIO gem

My code:
require 'rio'
rio('nice.jpg') < rio('http://farm4.static.flickr.com/3134/3160515898_59354c9733.jpg?v=0')
But the image downloaded is currupted. Whtat is wrong with this solution?
pjb3 is correct. You must call binmode on the left-hand term:
rio('nice.jpg').binmode < rio('http://...')
If this still does not work (notably, it may happen for large jpeg files, i.e. rio uses an intermediate temp file when retrieving from the URL you have provided), then apply the binmode modifier to both terms:
rio('nice.jpg').binmode < rio('http://...').binmode
2011 UPDATE
According to Luke C., the above answer no longer applies to more recent versions of the gem:
Neither of these work. On Linux having .binmode set on the destination causes a Errno::ENOENT exception. Doing: rio('nice.jpg') < rio('http://...').binmode works
It works for me. Are you on windows? It might be because the file isn't being opened with the binary flag.
I had similar problems downloading images on Linux, I found that this worked for me:
rio(source_url).binmode > rio(filename)
Here is some simple ruby code to download an image
require 'net/http'
url = URI.parse("http://www.somedomain.com/image.jpg")
Net::HTTP.start(url.host, url.port) do |http|
resp, data = http.get(url.path, nil)
open( File.join(File.dirname(__FILE__), "image.jpg"), "wb" ) { |file| file.write(resp.body) }
end
This can even be extended to follow redirects:
require 'net/http'
url = URI.parse("http://www.somedomain.com/image.jpg")
Net::HTTP.start(url.host, url.port) do |http|
resp, data = http.get(url.path, nil)
prev_redirect = ''
while resp.header['location']
raise "Recursive redirect: #{resp.header['location']}" if prev_redirect == resp.header['location']
prev_redirect = resp.header['location']
url = URI.parse(resp.header['location'])
host = url.host if url.host
port = url.port if url.port
http = Net::HTTP.new(host, port)
resp, data = http.get(url.path, nil)
end
open( File.join(File.dirname(__FILE__), "image.jpg"), "wb" ) { |file| file.write(resp.body) }
end
It can probably be prettied up some, but it gets the job done, and is not dependent on any 3rd party gems! :)
I guess this is a bug. On windows all 0x0A replaced with 0x0D 0x0A. And as so, it makes sence that properly used (with .binmode) it works on Linux.
For downloading pictures from the web page, you can use ruby gem image_downloader

Resources