Ruby-on-rails 将本地文件的内容读入 Rails 中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3055339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read contents of a local file into a variable in Rails
提问by Steven
All I want to do is get all the content from a local file and store it in a variable. How?
我想要做的就是从本地文件中获取所有内容并将其存储在一个变量中。如何?
File.read(@icon.full_filename).each {|l| r += l}
File.read(@icon.full_filename).each {|l| r += l}
only gives me a part of it. In PHP, I just used file_get_contents.
只给了我一部分。在 PHP 中,我只使用了file_get_contents.
采纳答案by Steven
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.
在这里回答我自己的问题......原来这是在读取二进制文件(在我的例子中是 JPEG)时发生的一个 Windows 怪癖,它需要在 open 或 File.open 函数调用中添加一个额外的标志。我修改了它open("/path/to/file", 'rb') {|io| a = a + io.read},一切都很好。
回答by zed_0xff
data = File.read("/path/to/file")
回答by Mehdi
I think you should consider using IO.binread("/path/to/file")if you have a recent ruby interpreter (i.e. >= 1.9.2)
我认为你应该考虑使用IO.binread("/path/to/file")如果你最近有一个 ruby 解释器(即 >= 1.9.2)
You could find IOclass documentation here http://www.ruby-doc.org/core-2.1.2/IO.html
你可以IO在这里找到类文档http://www.ruby-doc.org/core-2.1.2/IO.html

