diff --git a/inst/plumber/16-attachment/plumber.R b/inst/plumber/16-attachment/plumber.R index 87108148d..a4e825e1f 100644 --- a/inst/plumber/16-attachment/plumber.R +++ b/inst/plumber/16-attachment/plumber.R @@ -21,3 +21,30 @@ function() { function() { Sys.time() } + + +#* Write and return multiple files as an archive. Ex: `datasets.zip` +#* @serializer octet +#* @get /datasets +function() { + + # Create temporary directory structure + tmp_dir <- tempfile() + dir.create(tmp_dir, showWarnings = FALSE) + on.exit(unlink(tmp_dir, recursive = TRUE), add = TRUE) + + # Save datasets to csv + csv_files <- lapply(c("mtcars", "quakes", "airquality"), function(dataset) { + csv_file <- file.path(tmp_dir, paste0(dataset, ".csv")) + write.csv(get(dataset), csv_file) + csv_file + }) + + # Create archive + zip_file <- file.path(tmp_dir, "datasets.zip") + zip(zip_file, csv_files, flags = "-jq9X") + val <- readBin(zip_file, "raw", file.info(zip_file)$size) + + as_attachment(val, "datasets.zip") + +}