Detect Mime Type of Uploaded File in Ruby

Detect MIME type of uploaded file in Ruby

The ruby-filemagic gem will do it:

require 'filemagic'

puts FileMagic.new(FileMagic::MAGIC_MIME).file(__FILE__)
# => text/x-ruby; charset=us-ascii

This gem does not look at the file extension at all. It reads a bit of the file contents and uses that to guess the file's type.

How do I figure out the mime type without writing a file?

Assuming you are uploading file via html form, IO object should already have mime type, you can get it like that:

mime = params[:file].content_type

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

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

How to check in rails uploaded file type?

uploaded_io.content_type contains the MIME type of file.

So:

uploaded_io.content_type == "text/csv"

How to determine mime type by the file extension? ( Ruby )

You could use the mime-types gem:

puts MIME::Types.type_for('css')
=> [text/css]


Related Topics



Leave a reply



Submit