从url读取并写入Tempfile

时间:2014-05-27 20:45:40

标签: ruby temporary-files

说我有这个网址:Image

我想将其内容写入临时文件。我是这样做的:

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

但似乎tmp_file是空的。因为我这样做:

tmp_file.read => # ""

我错过了什么?

2 个答案:

答案 0 :(得分:7)

就这样做

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

tmp_file.rewind

tmp_file.read

查看documentation example

您的案例中的问题是您在IO的当前temp_file指针处执行读取,当您完成< EM>写入。因此,您需要在rewind之前执行read

答案 1 :(得分:3)

您需要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