1
#' Guess MIME type from filename (extension)
2
#'
3
#' Uses an internal database of over 1,800 file extension-to-MIME mappings to
4
#' return one or more associated types for a given input path. If no match is
5
#' found, `???` is returned.
6
#'
7
#' @md
8
#' @param path path to file
9
#' @param not_found MIME type to use when the content cannot be guessed by
10
#'        file type.
11
#' @param custom_db a single data frames each with two columns:
12
#'        `mime_type` and `extension`. These sources will be used along with
13
#'        the built-in sources and will take priority over the built-in sources.
14
#'        Note that the `extension`s should be lower case as they are in the
15
#'        official MIME database.
16
#' @return character vector
17
#' @export
18
#' @examples
19
#' guess_content_type(system.file("extdat", "test.pdf", package="wand"))
20
guess_content_type <- function(path, not_found = "???", custom_db = NULL) {
21

22 1
  path <- path.expand(path[1])
23 0
  if (!file.exists(path)) stop("File not found.", call.=FALSE)
24

25 1
  if (is.null(custom_db)) {
26 1
    db <- simplemagic_mime_db
27
  } else {
28

29 0
    if (inherits(custom_db, "data.frame")) {
30

31 0
      if (!all(c("mime_type", "extension") %in% colnames(custom_db))) {
32 0
        stop(
33 0
          "'custom_db' must have both 'mime_type' and 'extension' columns.",
34 0
          call.=FALSE
35
        )
36
      }
37

38 0
      rbind.data.frame(
39 0
        custom_db[, c("mime_type", "extension")],
40 0
        simplemagic_mime_db
41 0
      ) -> db
42

43 0
      db[["mime_type"]] <- as.character(db[["mime_type"]])
44 0
      db[["extension"]] <- as.character(db[["extension"]])
45

46
    } else {
47 0
      stop("'custom_db' must be data frame.", call.=FALSE)
48
    }
49

50
  }
51

52 1
  extension <- trimws(tolower(tools::file_ext(path)))
53

54 1
  res <- db[(db$extension == extension),]$mime_type
55

56 0
  if (length(res) == 0) return(not_found)
57

58 1
  return(unique(res))
59

60
}

Read our documentation on viewing source code .

Loading