| 1 |
#' Upload a File |
| 2 |
#' |
| 3 |
#' Upload a file to an `http://`, `ftp://`, or `sftp://` (ssh) |
| 4 |
#' server. Uploading to HTTP means performing an `HTTP PUT` on that URL. |
| 5 |
#' Be aware that sftp is only available for libcurl clients built with libssh2. |
| 6 |
#' |
| 7 |
#' @export |
| 8 |
#' @param file connection object or path to an existing file on disk |
| 9 |
#' @param url where to upload, should start with e.g. `ftp://` |
| 10 |
#' @param verbose emit some progress output |
| 11 |
#' @param reuse try to keep alive and recycle connections when possible |
| 12 |
#' @param ... other arguments passed to [handle_setopt()], for |
| 13 |
#' example a `username` and `password`. |
| 14 |
#' @examples \dontrun{# Upload package to winbuilder: |
| 15 |
#' curl_upload('mypkg_1.3.tar.gz', 'ftp://win-builder.r-project.org/R-devel/') |
| 16 |
#' } |
| 17 |
curl_upload <- function(file, url, verbose = TRUE, reuse = TRUE, ...) { |
| 18 |
infilesize <- NA |
| 19 |
con <- if(is.character(file)){ |
| 20 |
file <- normalizePath(file, mustWork = TRUE) |
| 21 |
infilesize <- file.info(file)$size |
| 22 |
base::file(file, open = 'rb') |
| 23 |
} else if(inherits(file, 'connection')){ |
| 24 |
file |
| 25 |
} else { |
| 26 |
stop("Parameter 'file' must be a ") |
| 27 |
} |
| 28 |
on.exit(close(con)) |
| 29 |
total_bytes <- 0 |
| 30 |
h <- new_handle(upload = TRUE, filetime = FALSE, readfunction = function(n) { |
| 31 |
buf <- readBin(con, raw(), n = n) |
| 32 |
total_bytes <<- total_bytes + length(buf) |
| 33 |
if(verbose){ |
| 34 |
if(length(buf) == 0 || identical(total_bytes, infilesize)){ |
| 35 |
cat(sprintf("\rUploaded %.0f bytes... all done!\n", total_bytes), file = stderr()) |
| 36 |
} else { |
| 37 |
cat(sprintf("\rUploaded %.0f bytes...", total_bytes), file = stderr()) |
| 38 |
} |
| 39 |
} |
| 40 |
return(buf) |
| 41 |
}, seekfunction = function(offset){ |
| 42 |
seek(con, where = offset) |
| 43 |
}, forbid_reuse = !isTRUE(reuse), verbose = verbose, ...) |
| 44 |
if(!is.na(infilesize)){ |
| 45 |
handle_setopt(h, infilesize_large = infilesize) |
| 46 |
} |
| 47 |
if(grepl('/$', url) && is.character(file)){ |
| 48 |
url <- paste0(url, basename(file)) |
| 49 |
} |
| 50 |
curl_fetch_memory(url, handle = h) |
| 51 |
} |