Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

693
Views
How to detect mime type of file in Rails in 2022?

Is there a built in way in Ruby/Rails to detect the mime type of a file given its URL, and not relying on its extension?

For example lets say there is an image file at an external URL that I want to get the mime type of: https://www.example.com/images/file

The file does not have an extension, but let's assume it is a jpeg.

How can I verify this/get the file's mime type in Rails? Would ideally love a way to do this with built in functionality and not have to rely on a third party gem.

I've looked over this question.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I don't think it's worth not using a third party gem for this. The problem space is well documented and stable, and most of the libraries are too.

But if you must, it can be done without an external gem. Especially if you're going to constrain yourself to a small subset of file types to "whitelist". The "magic number" pattern for most image files is pretty straightforward once you get the file on your disk:

image = File.new("filename.jpg","r")
irb(main):006:0> image.read(10)
=> "\xFF\xD8\xFF\xE0\x00\x10JFIF"

Marcel, which you linked in your reference, if nothing else, can be a great reference for the magic number sequences you'll need:

MAGIC = [
  ['image/jpeg', [[0, "\377\330\377"]]],
  ['image/png', [[0, "\211PNG\r\n\032\n"]]],
  ['image/gif', [[0, 'GIF87a'], [0, 'GIF89a']]],
  ['image/tiff', [[0, "MM\000*"], [0, "II*\000"], [0, "MM\000+"]]],
  ['image/bmp', [[0, 'BM', [[26, "\001\000", [[28, "\000\000"], [28, "\001\000"], [28, "\004\000"], [28, "\b\000"], [28, "\020\000"], [28, "\030\000"], [28, " \000"]]]]]]],
  # .....
]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!