将本地文件的内容读入 Rails 中的变量

我所要做的就是从一个本地文件中获取所有内容,并将其存储在一个变量中。怎么做到的?

File.read(@icon.full_filename).each {|l| r += l}

在 PHP 中,我只使用了 file_get_contents

117023 次浏览
data = File.read("/path/to/file")

Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read} and all was fine.

I think you should consider using IO.binread("/path/to/file") if you have a recent ruby interpreter (i.e. >= 1.9.2)

You could find IO class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html