FileType

github.comcoveralls.iohex.pmhex.pmhex.pmgithub.com

This package can be used to detect the MIME type and canonical extension by looking for magic numbers. It works by reading a small amount of data from the file (~256 bytes) and binary pattern matching against it’s contents.

API Documentation

Usage

Detecting a file’s type:

iex> FileType.from_path("profile.png")
{:ok, {"png", "image/png"}}

iex> FileType.from_path("contract.docx")
{:ok, {"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}}

Detect a file’s type from an IO:

iex> {:ok, file} = File.open("profile.png", [:read, :binary])
{:ok, file}

iex> FileType.from_io(file)
{:ok, {"png", "image/png"}}

Installation

The package can be installed by adding file_type to your list of dependencies in mix.exs:

def deps do
  [
    {:file_type, "~> 0.1.0"}
  ]
end

Supported types

Document

Image

Video

Audio

Font

Archive

Application

Executable

Other

Contributing

Most files can be detected with a single binary pattern match. To contribute support for new file type:

  1. Find an example file. Please make sure you have the rights to use this file.
  2. Register the fixture in test/file_type/integration_test.exs.
  3. Write some code to detect the file’s type in lib/file_type/magic.ex.
  4. Update the README to include a mention of your new file format.
  5. Send a pull request!

Please note that this library is not intended to detect text-based file formats like CSV, JSON, etc.

Prior Art