I want to create a download handler that updates the type and name of file to be downloaded based on user inputs. The only way I have found to do this in other queries is by having the user select the file type they want to download, however, I want this to be a function of the rest of the app.

Here is a simplified version of my code. It works well for one run, but then if you change the inputs at the top of the app, it still downloads with the original name and file format.

I have tried various combinations of reactives to no effect. If you try to make the content/filename etc. pieces of the download handler a call to a reactive function that throws up other issues, e.g.

library(plyr)
library(tidyr)
library(dplyr)
library(xlsx)
library(zoo)
library(shiny)


df_1 <- data.frame(x = c(1:5))
df_2 <- data.frame(x = letters[1:5])


server <- function(input, output, session) {

### which process?

output$a <- renderUI ({

selectInput(inputId = "a")


})

processed_file <- reactive({

if(input$a == 'Donorfy') {

  a <- df_1

} else if(input$a == 'Sage') {

  a <- df_2
}

 a
 })


output$download <- downloadHandler(


filename     = ifelse(input$a == 'Donorfy', gsub('-', '_', 
paste0('Sage_upload_', Sys.Date(), '.csv')),
                      gsub('-', '_', paste0('Donorfy_upload_', Sys.Date(), '.xlsx'))),

content      = ifelse(input$a == 'Donorfy',
                      function(file) {write.csv(processed_file(),file,  row.names = FALSE, na = '')},
                      function(file) {write.xlsx(processed_file(),file,  
                                                 showNA = FALSE, row.names = FALSE, sheetName = 'Donations')}),


contentType  = ifelse(input$a == 'Donorfy','text/csv', 
                      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

)

}


ui <- fluidPage(

h3('Simplified example app of reactive Downloadhandler'),

hr(),

fluidRow(

# Select Year
column(4, selectInput('a',label = "Which system are you moving data FROM?",
                      choices = c('','Donorfy', 'Sage'),
                      selected = '')),

column(4, selectInput('b',label = "Which system are you moving data TO?",
                      choices = c('','Donorfy', 'Sage'),
                      selected = ''))


),

fluidRow(

column(12,align="center", downloadButton(outputId = 'download', label = 'Convert and Download Files')) 

))



shinyApp(ui, server)

0 Answers