我正在使用 Rails 5 和 ruby-filemagic gem。如何从上传的文件中获取二进制数据?我的表单如下所示
<%= form_for @person, html: { multipart: true } do |f| %>
...
<div class="field">
<%= f.label :image %><br>
<%= f.file_field :image %>
</div>
我的 Controller 如下
def create
@person = Person.new(person_params)
if @person.image
cur_time_in_ms = DateTime.now.strftime('%Q')
file_location = "/tmp/file#{cur_time_in_ms}.ext"
File.binwrite(file_location, @person.image.tempfile)
fm = FileMagic.new(FileMagic::MAGIC_MIME)
@person.content_type = fm.file(file_location, true)
end
if @person.save
redirect_to @person
else
# This line overrides the default rendering behavior, which
# would have been to render the "create" view.
render "new"
end
end
但是当我查看文件的内容(我复制到“/tmp”目录中的文件)时,它显示...
#<ActionDispatch::Http::UploadedFile:0x007fba2573bbd0>
如何获取二进制数据(最好在“@person.image”属性中)?
最佳答案
点击p @person.image.methods
应该会产生您正在寻找的内容(我猜#read
)
关于ruby-on-rails - 如何在 Rails 5 中获取上传图像的二进制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309918/