在rails中查找上载文件的内容类型

use*_*non 3 bytearray paperclip stringio mime-types ruby-on-rails-3

我正在研究铁轨上的红宝石.我正在尝试做文件附件(图像/音频/视频).

所以我有一个常见的方法

byteArray = StringIO.new(File.open("path").read)
Run Code Online (Sandbox Code Playgroud)

是否可以找到byteArray的内容类型来检查上传的文件是否是ruby中的image/audio/video/pdf.

Ric*_*eck 6

我看到这是标记的paperclip,所以我会告诉你我们如何用回形针做到这一点:

class Attachment < ActiveRecord::Base

        has_attached_file :attachment,
                styles:          lambda { |a| a.instance.is_image? ? {:small => "x200>", :medium => "x300>", :large => "x400>"}  : {:thumb => { :geometry => "100x100#", :format => 'jpg', :time => 10}, :medium => { :geometry => "300x300#", :format => 'jpg', :time => 10}}},
                :processors => lambda { |a| a.is_video? ? [ :ffmpeg ] : [ :thumbnail ] }

        def is_video?
                attachment.instance.attachment_content_type =~ %r(video)
        end

        def is_image?
                attachment.instance.attachment_content_type =~ %r(image)
        end

end
Run Code Online (Sandbox Code Playgroud)

如果您设法将文件放入Paperclip,它基本上已将其切换为content_type.这意味着如果您使用a lambda来确定附件content_type是否包含imagevideo

如果你给我一些关于你想要实现什么的更多信息,我可以给你一些重构的代码来帮助解决你的问题:)