I am building an app that generates several Excel files in a folder, "out/". I would like to then zip these files and allow them to be downloaded by the user. The names of the files are dynamically generated, so I am using a list.files
function to build to list of files to be zipped. I tried following the advice from here, and while the app works, and I can see the CSV files are generated, the .zip file is not and the download offers me "downloadData" rather than the actual zip file.
Here is a reprex
library(shiny)
library(palmerpenguins)
library(tidyverse)
# Define UI
ui <- fluidPage(
# Application title
actionButton("button", "Zip!"),
downloadButton("downloadData", label = "Download")
)
# Define server
server <- function(input, output, session) {
observeEvent(input$button, {
#get list of names to loop through
species_names <- penguins %>% distinct(species) %>% pull() %>% as.character
#setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
# create CSVs
for(i in 1:length(species_names)){
species_check <- species_names[i]
penguins %>%
filter(species == species_check) %>%
write.csv(paste0("out/",species_check,".csv"))
}
#download button
output$downloadData <- downloadHandler(
#zip name
filename = "out/zip.zip",
#generate zip
content = function(fname) {
files <- list.files("out/")
for(i in 1:length(files)){
name <- paste0("out/",files[i])
fs <- c(fs, name)
}
zip(zipfile=fname, files=fs)
},
contentType = "application/zip"
)
})
}
# Run the application
shinyApp(ui = ui, server = server)