关于这个主题,SO上有许多不同的Q&A,但我没有找到适合我的用例的。我也很惊讶RStudio / Shiny开发人员自己没有发布一些关于如何做到这一点的文档。无论如何,看看这个示例应用程序:
library(shiny)
library(glue)
library(tidyverse)
# Define UI for application
ui <- fluidPage(
# Application title
titlePanel("Test Multi-File Download"),
p("I hope this works!"),
downloadButton(
outputId = "download_btn",
label = "Download",
icon = icon("file-download")
)
)
# Define server logic
server <- function(input, output) {
#datasets stored in reactiveValues list
to_download <- reactiveValues(dataset1 = iris, dataset2 = airquality, dataset3 = mtcars, dataset4 = NULL)
blahblah <- iris
output$download_btn <- downloadHandler(
filename = function(){
paste("my_data_", Sys.Date(), ".csv", sep = "")
},
content = function(file){
#works
#readr::write_csv(blahblah, file)
#Attempt 1
# #create some temp directory
# temp_directory <- tempdir()
# browser()
# reactiveValuesToList(to_download) %>%
# #x is data, y is name
# imap(function(x,y){
# #browser()
# #check if data is not null
# if(!is.null(x)){
# #create file name based on name of dataset
# file_name <- glue("{y}_data.csv")
# #write file to temp directory
# readr::write_csv(x, file_name)
# }
# })
# zip::zip(
# zipfile = file,
# files = ls(temp_directory),
# root = temp_directory
# )
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
我有一些数据集存储在
reactiveValues
列表中,我希望用户能够将它们全部下载。最好的情况是他们只需要一次性下载多个文件,而不必先将它们zip
起来并下载.zip
文件。另一个选择是将每个数据集添加到Excel工作表中,然后下载多页Excel文件。我的具体思路(前者)如下:
- 按下下载按钮
- 创建一个临时目录
- 将包含在
to_download
reactiveValues列表中的(非NULL
)数据集写入此目录 zip
这个临时目录并下载
setwd()
,因为我认为从Shiny应用程序内部更改工作目录是不良做法。
setwd()
是非常不好的做法。如果可能的话,我想尽量避免这种情况。 - Kyle Weisewritexl::write_xlsx()
,类似于我已经注释掉的方式,在imap()
内部进行操作,但是在提供一些条件来测试数据是否为NULL
时没有成功。 - Kyle Weise