Display download button in Shiny R only when output appears in Main Panel

Viewed 5499

I have the below code which allows to accept csv files -> run an R code -> display -> download the output.

But, the download button appears as soon as the app is run. is there a way to display the output button only when the output file is available?

Below is the code I am using:

UI.R

library(shiny)

#ui.R
# Define UI for random distribution application 
shinyUI(fluidPage(

  # Application title
  titlePanel("Text Mining on R"),

  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Select the Input File',
                accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
      tags$hr(),
      fileInput('file2', 'Select the UserTopic file',
                accept=c('text/csv','text/comma-separated-values,text/plain','.csv'))

    ),
    mainPanel(
      dataTableOutput('table'),
      downloadButton('OutputFile', 'Download Output File')
    )
  ))
)

Server.R

#server.R
library(shiny)

shinyServer(function(input, output) {

  observe({
    file1 = input$file1
    file2 = input$file2
    if (is.null(file1) || is.null(file2)) {
      return(NULL)
    }
    data1 = read.csv(file1$datapath,header = TRUE, sep=",",skipNul = TRUE)
    data2 = read.csv(file2$datapath,header = TRUE, sep=",",skipNul = TRUE)
   source("RCode.R", local = TRUE)
    #output$table <- renderDataTable(output2)
    output$table <- renderDataTable({
      my_function(file1$datapath,file2$datapath)
    })

    output$OutputFile <- downloadHandler(


      filename = function() {
        paste("OutputFile", "_",Sys.time(),".csv",sep="")
       },

      content = function(file) {


        write.csv(my_function(file1$datapath,file2$datapath), file, sep = ",",
                    row.names = FALSE)
      }
    )
  })

})

Thank you!

4 Answers

You can also use req().

In the UI:

uiOutput("get_the_item")

In the server:

output$get_the_item <- renderUI({
req(input$file1, input$file2)
downloadButton('download_item', label = 'Download item') })

Below the renderUI, add the downloadHandler (complete the code with your arguments for filename and content):

output$download_item <- downloadHandler(
filename = function() {},
content = function(file) {}
)
Related