Media Types

Get MIME type from string

mime-badge cat-encoding-badge

The following example shows how to parse a MIME type from a string using the mime crate. FromStrError produces a default MIME type in an unwrap_or clause.

extern crate mime;
use mime::{Mime, APPLICATION_OCTET_STREAM};

fn main() {
    let invalid_mime_type = "i n v a l i d";
    let default_mime = invalid_mime_type
        .parse::<Mime>()
        .unwrap_or(APPLICATION_OCTET_STREAM);

    println!(
        "MIME for {:?} used default value {:?}",
        invalid_mime_type, default_mime
    );

    let valid_mime_type = "TEXT/PLAIN";
    let parsed_mime = valid_mime_type
        .parse::<Mime>()
        .unwrap_or(APPLICATION_OCTET_STREAM);

    println!(
        "MIME for {:?} was parsed as {:?}",
        valid_mime_type, parsed_mime
    );
}

Get MIME type from filename

mime-badge cat-encoding-badge

The following example shows how to return the correct MIME type from a given filename using the mime crate. The program will check for file extensions and match against a known list. The return value is mime:Mime.

extern crate mime;
use mime::Mime;

fn find_mimetype (filename : &String) -> Mime{

    let parts : Vec<&str> = filename.split('.').collect();

    let res = match parts.last() {
            Some(v) =>
                match *v {
                    "png" => mime::IMAGE_PNG,
                    "jpg" => mime::IMAGE_JPEG,
                    "json" => mime::APPLICATION_JSON,
                    &_ => mime::TEXT_PLAIN,
                },
            None => mime::TEXT_PLAIN,
        };
    return res;
}

fn main() {
    let filenames = vec!("foobar.jpg", "foo.bar", "foobar.png");
    for file in filenames {
        let mime = find_mimetype(&file.to_owned());
        println!("MIME for {}: {}", file, mime);
     }

}

Parse the MIME type of a HTTP response

reqwest-badge mime-badge cat-net-badge cat-encoding-badge

When receiving a HTTP reponse from reqwest the MIME type or media type may be found in the Content-Type header. reqwest::Headers::get retrieves the header with the generic type reqwest::header::ContentType. Because ContentType implements Deref with mime::Mime as a target, parts of the MIME type can be obtained directly.

The Mime crate also has some, commonly used, predefined MIME types for comparing and matching. Reqwest also exports the mime crate, which can be found in the reqwest::mime module.

# #[macro_use]
# extern crate error_chain;
extern crate mime;
extern crate reqwest;

use reqwest::header::ContentType;
#
# error_chain! {
#    foreign_links {
#        Reqwest(reqwest::Error);
#    }
# }

fn run() -> Result<()> {
    let response = reqwest::get("https://www.rust-lang.org/logos/rust-logo-32x32.png")?;
    let headers = response.headers();

    match headers.get::<ContentType>() {
        None => {
            println!("The response does not contain a Content-Type header.");
        }
        Some(content_type) => {
            let media_type = match (content_type.type_(), content_type.subtype()) {
                (mime::TEXT, mime::HTML) => "a HTML document",
                (mime::TEXT, _) => "a text document",
                (mime::IMAGE, mime::PNG) => "a PNG image",
                (mime::IMAGE, _) => "an image",
                _ => "neither text nor image",
            };

            println!("The reponse contains {}.", media_type);
        }
    };

    Ok(())
}
#
# quick_main!(run);