将StringIO写入Tempfile

Har*_*ina 20 ruby io

我正在尝试使用ruby从url读取图像,然后将其保存Tempfile到以后进行处理.

require 'open-uri'

url = 'http://upload.wikimedia.org/wikipedia/commons/8/89/Robie_House.jpg'
file = Tempfile.new(['temp','.jpg'])
stringIo = open(url)
# this is part I am confused about how to save StringIO to temp file?
file.write stringIo
Run Code Online (Sandbox Code Playgroud)

这不起作用,导致temp.jpg无效的图像.不知道如何继续这个.

谢谢

Dyl*_*kow 35

你非常接近:

file.binmode
file.write stringIo.read
Run Code Online (Sandbox Code Playgroud)

open(url)正在打开阅读流.它实际上不会读取数据,直到你调用.read它(然后你可以传入file.write).

  • 谢谢你,超级喜欢嘿嘿爱那个.我也错过了`file.binmode`以防有人遇到类似的问题. (3认同)