ruby-on-rails - 如何在 Rails 5 中获取上传图像的二进制数据?

标签 ruby-on-rails image binary ruby-on-rails-5 multipartform-data

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

相关文章:

javascript - 如何将 Rails 变量传递到必须动态刷新(每 60 秒)的 View 的 CSS?

ruby-on-rails - 电子商务运输和帐单地址到 rails 中的一张表中

ruby-on-rails - 如何将 node js 应用程序包装到 rails gem 中

python - 关闭子图中的轴

html - 具有相对图像路径的外部 CSS 文件是否引用外部图像?

c# - 如何从 URL 获取数据并将其保存到 C#.NET 中的二进制文件中,而不会造成编码困惑?

ruby-on-rails - rake 数据库 :migrate - how do I undo all migrations and redo them

image - 如何使用 Ghostscript 调整 .eps 文件的大小

C# 二进制常量表示

c# - 如何将二进制数组转换为word格式并使用c#将其显示到textarea