如何检测 Rails 应用程序中的文件类型?

How to detect a file type in a Rails app?

我正在使用 Carrierwave 将图像、文档和视频上传到我的 s3 存储桶。至此上传图片和文档没问题。

在我看来,我想做的是确定文件类型,然后显示图像(我目前可以这样做)或提供文档图像,单击该图像后 download/open为用户复制该文件。

所以在我看来渲染图像我会这样做

 <% document.each do |doc| %>
   <%= link_to image_tag(doc.media_url(:thumb)) %> 
 <% end %>

但是我该怎么说呢

<% document.each do |doc| %>
  <% if doc.file_type == ['jpg', 'jpeg', 'png']
   <%= link_to image_tag(doc.media_url(:thumb)) %>
  <% else %>
    <%= link_to doc.media.path %> # This link downloading the file 
  <% end %>
<% end %>

嗯,在linux中,我也相信Mac,有确定文件类型的实用程序:

$ file filename.jpg
filename: JPEG image data, JFIF standard 1.02
$ file ./шрифты/шрифты/page-0020.png
filename.png: PNG image, 2512 x 3270, 8-bit grayscale, non-interlaced

所以在 ruby 中,您可以发出 %x() 方法来获取信息:

def type filename
   res = %x(file "#{File.expand_path(filename)}")
   m = res.match(/(.*): (.*)$/).to_a.last.split(' ').first.downcase
end

所以它会 return:

type "filename.jpg" # => jpeg
type "filename.png" # => png

windows 有些人应该使用 mingw/cygwin 安装。

我想(让其他人猜测你应该在你的问题中提供什么不是一件好事)你有一个模型文档并且你的上传者是媒体,就像这样:

class Document < ActiveRecord::Base
  mount_uploader :media, MediaUploader
end

如果是这种情况,您将获得每个文档的扩展名 (document.media.file.extension.downcase) 并将其与 'jpg'、'jpeg'、'png'[=15= 进行比较]

<% document.each do |doc| %>
  <% if ['jpg', 'jpeg', 'png'].include?(document.media.file.extension.downcase) %>
    <%= link_to image_tag(doc.media_url(:thumb)) %>
  <% else %>
    <%= link_to doc.media.path %> # This link downloading the file 
  <% end %>
<% end %>

如果您需要,Carrierwave 可以通过以下方式为您提供内容类型:

document.media.content_type # this returns image/png for a png file ...

编辑:

我认为更好的方法是这样检查(更干净):

<% document.each do |doc| %>
  <% if document.media.content_type =~ /image/ %>
    <%= link_to image_tag(doc.media_url(:thumb)) %>
  <% else %>
    <%= link_to doc.media.path %> # This link downloading the file 
  <% end %>
<% end %>