Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initiate downloadHandler with clientData in Shiny

Tags:

r

shiny

I have created a shiny app that uses session$clientData to get parameter values to the server. It works great, however, I would also like to be able to initiate a download through the url, e.g:

localhost:8100/?plot=a&title=mytitle&download=1

and then in server.R, something like:

if(session$clientData$download == "1"){
  download()
} 

Hence, is it possible to initiate the downloadHandler() in server.R?

Thanks!

like image 205
reinholdsson Avatar asked Aug 30 '13 21:08

reinholdsson


1 Answers

I am not sure I have correctly understood what you are trying to do. What I have understood is that you would like a download to be initiated when the query string download=1 is present in the url. You could do this by injecting some javascript to open the link when the required query string is detected. There will be some problems however. Your browser will most likely block the pop up. You will need to wait a sufficient length of time before you fire the code (I have chosen 5 seconds).

require(shiny)
runApp(list(
  ui = bootstrapPage(
    tags$head(tags$script(HTML('
      Shiny.addCustomMessageHandler("jsCode",
        function(message) {
          eval(message.value);
        }
      );
    '))),
    downloadLink('downloadData', 'Download'),
    verbatimTextOutput("summary")
  ),
  server = function(input, output, session) {
    data <- seq(100)
    output$downloadData <- downloadHandler(
      filename = function() {
        paste('data-', Sys.Date(), '.csv', sep='')
      },
      content = function(file) {
        write.csv(data, file)
      }
    )

    output$summary <- renderText({
      cnames <- names(session$clientData)

      allvalues <- lapply(cnames, function(name) {
        item <- session$clientData[[name]]
        if (is.list(item)) {
          list_to_string(item, name)
        } else {
          paste(name, item, sep=" = ")
        }
      })
      paste(allvalues, collapse = "\n")
    })

    observe({
      query <- parseQueryString(session$clientData$url_search)
      if(!is.null(query$download)){
        if(query$download == 1){
          jsinject <- "setTimeout(function(){window.open($('#downloadData').attr('href'))}, 5000);"
          session$sendCustomMessage(type = 'jsCode', list(value = jsinject))          
        }
      } 
    })
  }
))
like image 102
jdharrison Avatar answered Nov 17 '22 18:11

jdharrison