Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the content type of the uploaded file in rails

I am working on ruby on rails. I am trying to do a file attachment (image/audio/video) .

So i have a common method like

byteArray = StringIO.new(File.open("path").read)

Is it possible to find the content type of the byteArray to check whether the uploaded file is a image/audio/video/pdf in ruby.

like image 936
useranon Avatar asked Dec 11 '25 07:12

useranon


1 Answers

I saw this was tagged paperclip, so I will give you how we do it with 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

If you manage to get your file into Paperclip, it basically cuts it up into content_type already. This means that if you use a lambda to determine whether the attachment content_type contains image or video

If you give me some more info on what you're trying to achieve, I can give you some refactored code to help with your issue specifically :)

like image 147
Richard Peck Avatar answered Dec 14 '25 01:12

Richard Peck