Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from url and write to Tempfile

Say I have this url: Image

And I want to write its contents to a tempfile. I am doing it like this:

url =  http://s3.amazonaws.com/estock/fspid10/27/40/27/6/buddhism-hindu-religion-2740276-o.png
tmp_file = Tempfile.new(['chunky_image', '.png'])
tmp_file.binmode

open(url) do |url_file|
  tmp_file.write(url_file.read)
end

But it seems tmp_file is empty. Beacuse when I do:

tmp_file.read => # ""

What am I missing?

like image 987
Hommer Smith Avatar asked May 27 '14 20:05

Hommer Smith


2 Answers

Just do as

open(url) do |url_file|
  tmp_file.write(url_file.read)
end

tmp_file.rewind

tmp_file.read

Look at the documentation example.

The problem in your case was that you were doing a read at the current IO pointer in the temp_file, that is already at the end when you completed with writes. Thus you need to do a rewind before the read.

like image 133
Arup Rakshit Avatar answered Oct 10 '22 09:10

Arup Rakshit


You need tmp_file.rewind

url = "http://s3.amazonaws.com/estock/fspid10/27/40/27/6/buddhism-hindu-religion-2740276-o.png"
tmp_file = Tempfile.new(['chunky_image', '.png'])
tmp_file.binmode

open(url) do |url_file|
  tmp_file.write(url_file.read)
end

#You need to bring the cursor back to the start of the file with:

tmp_file.rewind

tmp_file.read 
like image 6
bjhaid Avatar answered Oct 10 '22 07:10

bjhaid