Bangyou
Bangyou

Reputation: 9816

Download file on Shiny.onInputChange

I am implementing a download link with Shiny.onInputChange which will send a message from client to server. The server will use the message to generate a new file, then provide to user to download. downloadHandler can create a button to download a file from server, but cannot receive message from client.

The Shiny.onInputChange can be captured by observeEvent.

My questtion is how to implement the download feature in the observeEvent.

There are some example codes for Shiny.onInputChange below. Thanks for any suggestions.

library(shiny)

ui <- shinyUI(
    fluidPage(
        HTML('<a href="#" onclick=\'Shiny.onInputChange("i_download", [1,Math.random()]);\'>Download</a>')
    )
)

server <- function(input, output, session) {
   observeEvent(input$i_download, {
       rep(input$i_download[1])
       # codes to generate a new file and download it
   })
}


shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 261

Answers (1)

Yang
Yang

Reputation: 191

I think you can receive the message using downloadHandler. Dose this meet your request:

library(shiny)

ui <- fluidPage(
  downloadLink('down', onclick='Shiny.onInputChange("i_download", [1,Math.random()]);')
  # for shiny 0.14.2 or lower use this instead:
  # tagAppendAttributes(downloadLink('down'),  onclick='Shiny.onInputChange("i_download", [1,Math.random()]);')
)

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

  output$down <- downloadHandler(

    filename = 'down.txt',

    content = function(file) {

      # use the message (input$i_download) to generate a new file

      writeLines(as.character(input$i_download), file)

    }
  )
}

shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions