| 1 |
#' POST files or data |
| 2 |
#' |
| 3 |
#' Build multipart form data elements. The `form_file` function uploads a |
| 4 |
#' file. The `form_data` function allows for posting a string or raw vector |
| 5 |
#' with a custom content-type. |
| 6 |
#' |
| 7 |
#' @param path a string with a path to an existing file on disk |
| 8 |
#' @param type MIME content-type of the file. |
| 9 |
#' @param name a string with the file name to use for the upload |
| 10 |
#' @export |
| 11 |
#' @name multipart |
| 12 |
#' @rdname multipart |
| 13 |
form_file <- function(path, type = NULL, name = NULL) { |
| 14 |
path <- enc2native(normalizePath(path[1], mustWork = TRUE)) |
| 15 |
if(!is.null(type)){ |
| 16 |
stopifnot(is.character(type)) |
| 17 |
} |
| 18 |
structure(list(path = path, type = type, name = name), class = "form_file") |
| 19 |
} |
| 20 |
|
| 21 |
#' @export |
| 22 |
#' @name multipart |
| 23 |
#' @rdname multipart |
| 24 |
#' @param value a character or raw vector to post |
| 25 |
form_data <- function(value, type = NULL){ |
| 26 |
if(is.character(value)) |
| 27 |
value <- charToRaw(paste(enc2utf8(value), collapse = "\n")) |
| 28 |
if(!is.raw(value)) |
| 29 |
stop("Argument 'value' must be string or raw vector") |
| 30 |
structure(list(value = value, type = type), class = "form_data") |
| 31 |
} |
| 32 |
|
| 33 |
#' @export |
| 34 |
print.form_file <- function(x, ...){ |
| 35 |
txt <- paste("Form file:", basename(x$path)) |
| 36 |
if(!is.null(x$name)) { |
| 37 |
txt <- sprintf("%s => %s", txt, x$name) |
| 38 |
} |
| 39 |
if(!is.null(x$type)){ |
| 40 |
txt <- sprintf("%s (type: %s)", txt, x$type) |
| 41 |
} |
| 42 |
cat(txt, "\n") |
| 43 |
} |
| 44 |
|
| 45 |
#' @export |
| 46 |
print.form_data <- function(x, ...){ |
| 47 |
txt <- paste(sprintf("Form data of length %.0f", length(x$value))) |
| 48 |
if(!is.null(x$type)){ |
| 49 |
txt <- sprintf("%s (type: %s)", txt, x$type) |
| 50 |
} |
| 51 |
cat(txt, "\n") |
| 52 |
} |