Rails 5 如何获取上传图片的二进制数据?

How do I get the binary data of an uploaded image in Rails 5?

我正在使用 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>

我的控制器如下

  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