Mime type detection by magic numbers

if i put the file into the project folder then it works

At first Iā€™d need some reliable source of such magic numbers and their mapping to MIME-types.

itā€™s already on your computer

/usr/share/mime/magic contains the compiled informations about magic numbers while /usr/share/mime/globs all the glob patterns.

file --mime-type results are as reliable as the databases on your system is good.

The database is populated by the applications installing their own mime specifications or manually by creating the correct XML files and then running update-mime-database.

but I donā€™t think that a sequential pattern match is fast enough.

On my system magic is not that big

wc -l /usr/share/mime/magic 
1767 /usr/share/mime/magic

Half of the lines are taken by mime definitions, so in total itā€™s less than a thousand patterns.

wc -l /etc/mime.types 
846 /etc/mime.types

Even testing all of them sequentally should be fast enough.

figured it out,

Could you please tell us your solution?

4 Likes
%Plug.Upload{
  content_type: "application/pdf",
  filename: "random-grid.pdf",
  path: "/tmp/plug-1569/multipart-1569289758-138513881763554-3"
}

The path includes the filename alreadyā€¦ adding filename results in an error.

precisely, I was trying to use the filename from plug, you need to use the path

Your wrapper is probably a much more sane solution than this, but just for fun I wrote an example of how this could be done in pure Elixir using the fun of pattern matching.

Hi, Iā€™ve just implemented this GitHub - chaskiq/ex-marcel: Find the mime type of files, examining file, filename and declared type, itā€™s a port from Rails Marcel gem, the library gives the mime type by looking at the magic bytes but also by name or extension as fallbacks.
Itā€™s just a pure elixir library, dependency-free.

2 Likes