Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

692
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda