rails/marcel: Find the mime type of files, examining file, filename and declared type

19-Sep-2025 1531
Marcel chooses the most appropriate content type for a file by inspecting its contents, the declared MIME type (perhaps passed as a Content-Type header), and the file extension. Marcel checks, in order: The "magic bytes" sniffed from the file contents. The declared type, typically provided in a Content-Type header on an uploaded file, unless it's the application/octet-stream default. The filename extension. Safe fallback to the indeterminate application/octet-stream default. At each step, the most specific MIME subtype is selected. This allows the declared type and file extension to refine the parent type sniffed from the file contents, but not conflict with it. For example, if "file.csv" has declared type text/plain, text/csv is returned since it's a more specific subtype of text/plain. Similarly, Adobe Illustrator files are PDFs internally, so magic byte sniffing indicates application/pdf which is refined to application/illustrator by the ai file extension. But a PDF named "image.png" will still be detected as application/pdf since image/png is not a subtype.
Use coupon code:

RUBYONRAILS

to get 30% discount on our bundle!
Prepare for your next tech interview with our comprehensive collection of programming interview guides. Covering JavaScript, Ruby on Rails, React, and Python, these highly-rated books offer thousands of essential questions and answers to boost your interview success. Buy our 'Ultimate Job Interview Preparation eBook Bundle' featuring 2200+ questions across multiple languages. Ultimate Job Interview Preparation eBook Bundle