加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在不编写文件的情况下找出mime类型?

发布时间:2020-12-17 03:25:22 所属栏目:百科 来源:网络整理
导读:这是使用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 =
这是使用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

解决方法

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

mime = params[:file].content_type

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读