Skip to content

Commit

Permalink
Add a zip attachment example (#922)
Browse files Browse the repository at this point in the history
  • Loading branch information
meztez authored Nov 17, 2023
1 parent 8cf3177 commit 0c59025
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions inst/plumber/16-attachment/plumber.R
Original file line number Diff line number Diff line change
Expand Up @@ -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")

}

0 comments on commit 0c59025

Please sign in to comment.