Some code shared by @jeroen in a Slack conversation about use_course()
library(curl)
download_with_cd <- function(url, destdir = "."){
h <- new_handle(noprogress = FALSE)
tmp <- tempfile()
curl::curl_fetch_disk(url, tmp, handle = h)
headers <- curl::parse_headers_list(handle_data(h)$headers)
filename <- stringr::str_match(headers[["content-disposition"]], "filename=.*")[1]
filename <- sub("filename=", "", filename)
outfile <- normalizePath(file.path(destdir, filename), mustWork = FALSE)
file.rename(tmp, outfile)
return(outfile)
}
download_with_cd("https://cran.ocpu.io/ggplot2/data/diamonds/csv", destdir = "~")
Other notes:
- If you use
curl_fetch_disk you can check the status code also from handle_data().
- Using
curl_download() might be easier -- automatically throws an error if the result is not http 200
- the trick is all functions in curl take a handle, and you can always use
handle_data() to access the metadata after the request
Some code shared by @jeroen in a Slack conversation about
use_course()Other notes:
curl_fetch_diskyou can check thestatuscode also fromhandle_data().curl_download()might be easier -- automatically throws an error if the result is not http 200handle_data()to access the metadata after the request