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
Find Out If Current Time Is Between Two Times
To_D to Always Return 2 Decimals Places in Ruby
Difference Between Include and Require in Ruby
How to Reload the Current Page in Ruby on Rails
Validation for Non-Negative Integers and Decimal Values
How to Convert a Bigdecimal to a 2-Decimal-Place String
Case Statement With Multiple Values in Each 'When' Block
Cannot Load Such File - Zlib Even After Using Rvm Pkg Install Zlib
Is Ruby Pass by Reference or by Value
Why Do Ruby Setters Need "Self." Qualification Within the Class
How to Dynamically Create a Local Variable
Eventsource/Server-Sent Events Through Nginx
You Have Already Activated X, But Your Gemfile Requires Y
Backslashes in Single Quoted Strings Vs. Double Quoted Strings