File type detection from content (magic bytes), file extension, and MIME type mapping
cargo add philiprehberger-mime-detectFile type detection from content (magic bytes), file extension, and MIME type mapping
[dependencies]
philiprehberger-mime-detect = "0.3.0"
use philiprehberger_mime_detect::{detect_from_bytes, detect_from_extension, detect_from_filename, FileKind};
// Detect from content
let png_header = &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
let file_type = detect_from_bytes(png_header).unwrap();
assert_eq!(file_type.mime_type(), "image/png");
assert_eq!(file_type.extension(), "png");
assert!(file_type.is_image());
// Detect from extension
let file_type = detect_from_extension("json").unwrap();
assert_eq!(file_type.mime_type(), "application/json");
// Detect from filename
let file_type = detect_from_filename("report.pdf").unwrap();
assert_eq!(file_type.mime_type(), "application/pdf");
// Detect from file path (reads content, falls back to extension)
let file_type = philiprehberger_mime_detect::detect_from_path("photo.jpg".as_ref());
use philiprehberger_mime_detect::{mime_to_extension, extension_to_mime, all_extensions_for_mime};
assert_eq!(mime_to_extension("image/png"), Some("png"));
assert_eq!(extension_to_mime("html"), Some("text/html"));
// All known extensions for a MIME type (e.g. jpg + jpeg, mid + midi)
let exts = all_extensions_for_mime("image/jpeg");
assert!(exts.contains(&"jpg") && exts.contains(&"jpeg"));
| Function | Description |
|---|---|
detect_from_bytes(bytes) | Detect type from magic bytes |
detect_from_extension(ext) | Detect type from file extension |
detect_from_filename(name) | Detect type from a filename string |
detect_from_path(path) | Detect from file (content + extension) |
detect_from_reader(reader, limit) | Detect from a reader |
mime_to_extension(mime) | Get default extension for MIME type |
all_extensions_for_mime(mime) | Get every known extension for a MIME type |
extension_to_mime(ext) | Get MIME type for extension |
FileType::is_image/is_video/is_audio/is_archive/is_text | Category checks for common kinds |
FileType::is_document/is_font/is_executable | Category checks for the remaining kinds |
cargo test
cargo clippy -- -D warnings
If you find this project useful: