【问题标题】:How do I figure out the mime type without writing a file?如何在不写入文件的情况下找出 MIME 类型?
【发布时间】:2018-06-26 21:28:44
【问题描述】:

这适用于 Rails 5 和 ruby​​-filemagic。目前,除了 mime 类型之外,我还将上传的图像保存到我的数据库中。我的控制器中有这段代码

  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.read)
      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

用这种方法困扰我的是我必须在确定文件的 mime 类型之前将文件写入文件系统。这似乎很浪费。如何在不先创建文件的情况下确定 mime 类型?

编辑:响应给出的答案,我重新安排了一些东西,但现在“content_type”变成了“application/x-empty”,即使我上传了一个有效的 png 文件。这是代码

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.read)
  file = File.open(file_location, "rb")
  contents = file.read
  # Scale image appropriately
  #img = Magick::Image::read(file_location).first
  @person.content_type = FileMagic.new(FileMagic::MAGIC_MIME).buffer(@person.image.read, true)
  @person.image = contents

【问题讨论】:

  • 您指的是接受的答案吗?在其中,他们仍在引用一个文件——“FileMagic.new(FileMagic::MAGIC_MIME).file(FILE)”,而不是仅仅从二进制数据中找出文件类型。我弄错了吗?
  • 如果你这样做FileMagic.new(FileMagic::MAGIC_MIME).file(@person.image.read)会发生什么?我不熟悉 FileMagic,但 应该 可以工作。
  • 当我尝试得到错误时,“无法打开`\211PNG\015\012\032\012'(没有这样的文件或目录)”
  • 根据您使用的库,我认为@person.image 已经是一个临时文件。你能试试fm.file(@person.image.path, true)吗?对于真正的 IO 数据,您需要 fm.buffer

标签: ruby-on-rails image ruby-on-rails-5 mime-types


【解决方案1】:

假设你通过html表单上传文件,IO对象应该已经有mime类型,你可以这样获取:

mime = params[:file].content_type

【讨论】:

  • 它实际上是@person.image.content_type 但足够接近。
【解决方案2】:

尝试使用buffer 方法而不是文件,即FileMagic.new(FileMagic::MAGIC_MIME).buffer(@person.image.read, true)

【讨论】:

  • 嗨,我尝试了这一行,但出现错误,“未定义的方法 `read' for #<0x007f89d3889eb0>
猜你喜欢
  • 2013-06-08
  • 2010-11-04
  • 2011-01-14
  • 1970-01-01
  • 2020-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
相关资源
最近更新 更多