View Source MimeSniff (mime_sniff v0.1.1)

A MIME Type detection by magic number in Elixir.

Link to this section Summary

Functions

Sniff a MIME Type from input binary.

Sniff a MIME Type from file for the given path.

Link to this section Types

@type sniff_opt() :: {:sniff_len, integer()} | {:custom_signatures, term()}

Link to this section Functions

Link to this function

from_binary(data, opts \\ [])

View Source
@spec from_binary(binary(), [sniff_opt()]) :: {:ok, String.t()} | {:error, atom()}

Sniff a MIME Type from input binary.

options

Options

  • :sniff_len - set how many bytes of data from the head that should be use to determine the MIME Type (default 32).

    If this value is less than byte_size(data) only data[:sniff_len] will be used; Otherwise, the whole data will be used

  • :custom_signatures - a list of Struct that implemented MimeSniff.Signatures.Signature the given list will be given more priority than the default signature as ordered in Support types section. (see MimeSniff.Signatures.Signature for more information of how to create custom Signature)

examples

Examples

iex> bin = <<104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 115, 33>> # hello worlds!
iex> MimeSniff.from_binary(bin)
{:ok, "text/plain"}

# for sniff_len and custom_signatures, see examples in from_binary/2
Link to this function

from_file(file_path, opts \\ [])

View Source
@spec from_file(String.t(), [sniff_opt()]) :: {:ok, String.t()} | {:error, atom()}

Sniff a MIME Type from file for the given path.

options

Options

same as from_binary/2

examples

Examples

iex> MimeSniff.from_file("support/fixtures/png_file.png")
{:ok, "image/png"}

# example for sniff_len
# only read 32 bytes, if not provided default is 32 bytes
iex> MimeSniff.from_file("support/fixtures/jpg_file.jpg", sniff_len: 16)
{:ok, "image/jpeg"}

# example for custom_signatures
# MimeSniff.Signatures.ExactSignature struct implemented MimeSniff.Signatures.Signature
# utf8_file.txt contain a string "UTF8"
iex> alias MimeSniff.Signatures.ExactSignature
iex> custom_utf8_sig = %ExactSignature{byte_pattern: "UTF8", mime_type: "custom/utf8"}
iex> custom_utf16_sig = %ExactSignature{byte_pattern: "UTF16", mime_type: "custom/utf16"}
iex> MimeSniff.Sniffing.from_file("support/fixtures/utf8_file.txt")
{:ok, "text/plain"}
iex> MimeSniff.Sniffing.from_file("support/fixtures/utf8_file.txt", custom_signatures: [custom_utf16_sig, custom_utf8_sig])
{:ok, "custom/utf8"}