5

I am looking for a way to download text displayed on an app by generation a .txt file. Here is my attempt, with no success unfortunately:

library(shiny)

ui <- fluidPage(

    sidebarPanel(
      h4("Title"),
      p("Subtitle",
        br(),"Line1",
        br(),"Line2",
        br(),"Line3"),

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

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

    output$downlaodData <- downloadHandler(
      filename = function(){
        paste("data-", Sys.Date(), ".txt", sep = "")
      },
      content = function(file) {
        write.txt(data, file)
      }
    )

Thank you for your help

MaxPlank
  • 185
  • 2
  • 13

1 Answers1

5

You cannot write text that is displayed on your page like that. You could download text stored as data or as user input. There are also some issues in your code:

  • data is not defined, so you are not specifying what should be downloaded
  • write.txt is not a function, use write.table instead
  • The downloadbutton and the downloadHandler should have the same id.

Working example

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)
Florian
  • 24,425
  • 4
  • 49
  • 80
  • The issue with this method is that it will output quotation marks and any escapes; that is, it writes the text verbatim to file. Say R has a string `test <- "this is a \"test\""`. Using this method preserves the quotation marks at the front and end as well as the escapes. Is there a way to not do this? – Mark White Jun 21 '18 at 21:03
  • Ah. Replace `write.table(paste(text,collapse=", "), file,col.names=FALSE)` with `writeLines(paste(text, collapse = ", "), file)` – Mark White Jun 21 '18 at 21:08
  • 1
    @MarkWhite I think `writeLines` is a nicer solution, thanks for the feedback. I have updated the answer accordingly. – Florian Jun 22 '18 at 06:38