3

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.

useranon
  • 29,318
  • 31
  • 98
  • 146
  • Are you using paperclip for file uploading? – Ramiz Raja Mar 05 '13 at 06:18
  • @Ramiz Raja ya once i set the content type for the attachment , i used to save it via paperclip. Currently i have 3 separate methods for saving one for images, audio and video. So i am trying to generalize it so that to find the content type of the byteArray and to set the content type and save it in Paperclip – useranon Mar 05 '13 at 06:26
  • 2
    you can get `content type` of uploaded file as `paperclip` generate column `_content_type` for the uploaded file. – Ramiz Raja Mar 05 '13 at 07:57
  • Are you looking to restrict upload by file type? – Btuman Jun 26 '13 at 15:39

1 Answers1

7

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 :)

Richard Peck
  • 76,116
  • 9
  • 93
  • 147