Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shiny DownloadHandler doesn't update filename using Sys.time()

Tags:

r

download

shiny

How do you get a downloadHandler in shiny to update the value of filename after every click on the download button? I try to construct a unique filename using Sys.time. Alas, Sys.time() appears to be executed only once when the Shiny app is opened. Hence, an attempt to download the file a second time doesn't give a new filename, it just gives a [1] at the end of the file name.

Minimal reproducible example below:

library(shiny)

if (interactive()) {

  ui <- fluidPage(
    downloadButton("downloadData", "Download")
  )

  server <- function(input, output) {
    # Our dataset
    data <- mtcars

    output$downloadData <- downloadHandler(
      filename = paste("example",gsub(":","-",Sys.time()), ".csv", sep=""),
      content = function(file) {
        write.csv(mtcars,file)
      }
    )
  }

  runApp(list(ui=ui,server=server),launch.browser=T)
}

Make sure you try to download the file a second time within the same instance, checking the name on the file.

like image 488
Jason Dealey Avatar asked Mar 29 '17 14:03

Jason Dealey


1 Answers

This is because you don't give a function but a value as argument for filename. That's the reason you always have the same filename: a value is assigned when the downloadHandler is initiated, whereas a function is evaluated at every click on the downloadButton.

So wrap your code for the filename in a function, and your problem is solved:

library(shiny)

if (interactive()) {

  ui <- fluidPage(
    downloadButton("downloadData", "Download")
  )

  server <- function(input, output) {
    # Our dataset
    data <- mtcars

    output$downloadData <- downloadHandler(
      filename = function(){
        paste("example",gsub(":","-",Sys.time()), ".csv", sep="")
        },
      content = function(file) {
        write.csv(mtcars,file)
      }
    )
  }

  runApp(list(ui=ui,server=server),launch.browser=T)
}

This information can also be found on the following article of RStudio:

https://shiny.rstudio.com/articles/download.html

like image 133
Joris Meys Avatar answered Sep 24 '22 13:09

Joris Meys