【问题标题】:Read from url and write to Tempfile从 url 读取并写入 Tempfile
【发布时间】:2014-05-27 20:45:39
【问题描述】:

假设我有这个网址: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 => # ""

我错过了什么?

【问题讨论】:

    标签: ruby temporary-files


    【解决方案1】:

    照做

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

    看看documentation example

    您的问题是您正在对 temp_file 中的当前 IO 指针进行 read,当您完成 writes。因此,您需要在read 之前执行rewind

    【讨论】:

    • 值得注意的是,read 从文件中的当前偏移处读取,写入后即结束。 rewind 回到开头。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-12-07
      • 1970-01-01
      • 2018-06-23
      • 2013-08-15
      • 2015-08-04
      • 2021-10-19
      • 1970-01-01
      • 2018-12-28
      • 2018-10-24
      相关资源
      最近更新 更多