firmo23
firmo23

Reputation: 8454

How to set filename of your choice when you download file from shiny app

I have a simple shiny app which downloads a .txt file. My problem is that I want to be able to set the filename from the app and download it as filename.txt for example and not "download_button" as it is now.

library(shiny)

text=c("Line1", "Line2","Line3")

ui <- fluidPage(

  sidebarPanel(
    h4("Title"),
    p("Subtitle",
      br(),text[1],
      br(),text[2],
      br(),text[3]),

    downloadButton("download_button", label = "Download")
  )
)

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

  output$download_button <- downloadHandler(
    filename = function(){
      paste("data-", Sys.Date(), ".txt", sep = "")
    },
    content = function(file) {
      writeLines(paste(text, collapse = ", "), file)
      # write.table(paste(text,collapse=", "), file,col.names=FALSE)
    }
  )
}

shinyApp(ui,server)

Upvotes: 1

Views: 2175

Answers (1)

phalteman
phalteman

Reputation: 3542

Hopefully this addresses your issue. I just included a text input with the default value set to your filename as above, and then set the filename in the download function to that text input.

text=c("Line1", "Line2","Line3")

ui <- fluidPage(

  sidebarPanel(
    h4("Title"),
    p("Subtitle",
      br(),text[1],
      br(),text[2],
      br(),text[3]),
    textInput("filename", "Input a name for the file", value = paste0("data-", Sys.Date(),".txt")),
    downloadButton("download_button", label = "Download")
  )
)

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

  output$download_button <- downloadHandler(
    filename = function(){
      input$filename
    },
    content = function(file) {
      writeLines(paste(text, collapse = ", "), file)
    }
  )
}

shinyApp(ui,server)

Upvotes: 1

Related Questions