Nancy Moore
Nancy Moore

Reputation: 2470

Mime Type file checking only fails when uploading using Ruby on Rails

I use this code to upload files to server and it's working fine.

Now am trying to check mime file types before allowing files upload using carrierwaves function.

I try using Ruby Filemagic() as suggested in solution found here link but seems to be outdated as it requires Ruby version less than 2.5.0

My success

I try using Ruby MIME::Types.type_for() validation.

It works fine when reading files directly from disk as per code below

check=MIME::Types.type_for("C:/Users/Public/Pictures/Sample Pictures/america.jpg").first.content_type

My issues

If I try reading the files as part of form upload, it will display error

undefined method `chomp' for #<ActionDispatch::Http::UploadedFile:0x0953a828>

as per code below

check=MIME::Types.type_for(image_params['attachment']).first.content_type

It seems pattern of checking when reading files from disk is different when reading files as part of form uploads. I guess something like mime vs content_type.

Here is image_controller

class ImagesController < ApplicationController

   def create


      print(' para: ', image_params['name'])
      print(' para: ', image_params['attachment'])

      #check=MIME::Types.type_for("C:/Users/Public/Pictures/Sample Pictures/america.jpg").first.content_type
      check=MIME::Types.type_for(image_params['attachment']).first.content_type
      print(check)

      @imagefile = Imagefile.new(image_params)

      if @image.save
         redirect_to images_path, notice: "file has been uploaded."
      else
         render "new"
      end

   end

   private
      def image_params
      params.require(:image).permit(:name, :attachment)
   end

end

Attachment _controller

class AttachmentUploader < CarrierWave::Uploader::Base

   storage :file

    def store_dir
       "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
   end

   def extension_white_list
      %w(pdf doc htm html docx png jpg gif)
   end

image model

class Image < ApplicationRecord
   mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model.

   validates :name, :attachment, presence: true # Make sure the owner's name is present.

end

Upvotes: 0

Views: 875

Answers (1)

Nancy Moore
Nancy Moore

Reputation: 2470

mimemagic gem is what works for me

The library to detect the mime type of a file by extension and by content.

source

detects mimetypes by using extension name

 MimeMagic.by_path('nancy.png')

detects mimetype by reading the file content

  MimeMagic.by_magic(File.open('nanc.png'))

Upvotes: 1

Related Questions