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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With