I have a shiny app that generates various tables of data and each is triggered by an action button in the UI and an observe event in the server. I am trying to add several download handlers so users can download the data tables as csv files. In my app, when I push on the download button, the app downloads "download.html" with the content of the app UI. I have checked the names of my button ID and it matches my download handler so it is not the problem as discussed here: https://stackoverflow.com/a/42583662/7565465
My app code is long so I have made a toy example that illustrates more or less how the app works. I have data frames that are created inside an observe event when an action button is clicked. In my toy example below, the download handler 1) does not assign the right name; it assigns d1.txt or d2.txt (rather than data1.csv and data2.csv) respectively. 2) The file will not open and chrome tells me "Failed - Server problem." I recognize that this is not the exact behavior of what happens when I go to download in my actual app (i.e., the "download.html" issue) but I assume that the two are similar, and I am hoping that if someone can help me understand what is wrong with my toy example below, that I can get on the right path to solving my problems. Thanks!!!
ui <- fluidPage(
# App title ----
titlePanel("Hello Shiny!"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
actionButton("button1", "click me 1"), br(),
actionButton("button2", "click me 2"), br(),
downloadButton("d1", "Download Data 1"), br(),
downloadButton("d2", "Download Data 2")
),
mainPanel(
helpText("Tables will apear when you push 'click me'"),
br(),
tableOutput("table1"),
br(),
tableOutput("table2")
)))
server <- function(input, output, server) {
observeEvent(input$button1, {
mydata1 <- data.frame (col1 = c(1:4),
col2 = letters[1:4],
stringsAsFactors = FALSE)
output$table1 <- renderTable( mydata1)
})#close observerEvent1
observeEvent(input$button2, {
mydata2 <- data.frame (col1 = c(5:8),
col2 = letters[5:8],
stringsAsFactors = FALSE)
output$table2 <- renderTable( mydata2)
}) #close observerEvent2
#download data 1
output$d1 <- downloadHandler(
filename = function() {
"data1.csv"
},
content = function(file) {
write.csv(mydata1, file, row.names = FALSE)
}
)
#download data 2
output$d2 <- downloadHandler(
filename = function() {
"data2.csv"
},
content = function(file) {
write.csv(mydata2, file, row.names = FALSE)
}
)
}
#open directly in browser
runApp(list(ui = ui, server = server), launch.browser = T)