shiny app : disable downloadbutton

后端 未结 2 1838
花落未央
花落未央 2020-12-31 16:37

My shiny app produces some files that user can download. I have put downloadbutton in the ui for this purpose. However, when the page launches and before any calculation is

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-31 16:52

    Based on your comment:

    yes data processing depends on the user input. USer will upload some files and click anAction button to start the processing. The download button is in a tab set.

    Let's say the action button is named input$start_proc.

    In server.R:

    shinyServer(function(input, output, session) {
       #... other code
       observe({
           if (input$start_proc > 0) {
               # crunch data...
               # when data is ready:
               session$sendCustomMessage("download_ready", list(...))
               # you can put extra information you want to send to the client 
               # in the ... part.
           } 
       })
       #... other code
    })
    

    Then in ui.R, you can write some javascript to handler the custom message event.


    A full example is:

    server.R

    library(shiny)
    
    fakeDataProcessing <- function(duration) {
      # does nothing but sleep for "duration" seconds while
      # pretending some background task is going on...
      Sys.sleep(duration)
    }
    
    shinyServer(function(input, output, session) {
    
      observe({
        if (input$start_proc > 0) {
          fakeDataProcessing(5)
          # notify the browser that the data is ready to download
          session$sendCustomMessage("download_ready", list(fileSize=floor(runif(1) * 10000)))
        }
      })
    
      output$data_file <- downloadHandler(
           filename = function() {
             paste('data-', Sys.Date(), '.csv', sep='')
           },
           content = function(file) {
             write.csv(data.frame(x=runif(5), y=rnorm(5)), file)
           }
      )
    })
    

    ui.R

    library(shiny)
    
    shinyUI(fluidPage(
      singleton(tags$head(HTML(
    '
      
    '
    ))),
      tabsetPanel(
        tabPanel('Data download example',
          actionButton("start_proc", h5("Click to start processing data")),
          hr(),
    
          downloadButton("data_file"),
          helpText("Download will be available once the processing is completed.")
        )
      )
    ))
    

    In the example the data processing is faked by waiting for 5 seconds. Then the download button will be ready. I also added some "fake" fileSize information in the message to demonstrate that how you can send extra information to the user.

    Note that because Shiny implements actionButton as tag instead of

提交回复
热议问题