How to remove folders after download compeleted

I want to build a shiny app that it stores something in a folder which can be downloaded. After download completed, the folder created should be remove. I just don't know how to remove the folder in final step so I need your help. Below is my code:

library(shiny)

ui <- fluidPage(
  textInput("id", "ID", "1335913"),
  downloadButton("download", "Download")
)

server <- function(input, output, session) {
  output$download <- downloadHandler(
    filename = function() {
      paste0(input$id, ".zip")
    },
    content = function(file) {
      dir.create(input$id)
      write.csv(mtcars, paste0(input$id, "/mtcars.csv"))
      zip(file, input$id)
    },
    contentType = "application/zip"
  )
}

shinyApp(ui, server)

Hi @eyoki. R didn't provide remove directory function, so may try to use system function to invoke the command rm -rf path/to/folderName.

Hi,

Another option is setting a temp folder and zipping from there. This will be automatically deleted anyway.

library(shiny)

ui <- fluidPage(
  textInput("id", "ID", "1335913"),
  downloadButton("download", "Download")
)

server <- function(input, output, session) {
  output$download <- downloadHandler(
    filename = function() {
      paste0(input$id, ".zip")
    },
    content = function(file) {
      myDir = tempdir()
      write.csv(mtcars, paste0(myDir, "/mtcars.csv"))
      zip(file, paste0(myDir, "/mtcars.csv"), flags = "-r9Xj")
    },
    contentType = "application/zip"
  )
}

shinyApp(ui, server)

Note that I added to the flags argument a j (j for junk path) to ensure that the folder structure does not get saved in the zip, just the file.

PJ

1 Like

Actually base R unlink() function it allows you to remove folders recursively

2 Likes

Hi @andresrcs. I didn't know this unlink() function before. :sweat_smile: I know how to remove folder in the future. Thank you for your information!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.