Sebastian Zeki
Sebastian Zeki

Reputation: 6874

Get the path for a folder chosen by user in shiny

I would like the user to be able to choose a folder (Ill retrieve the path for this later).

At the moment this works for selection of a file but not a folder. I cant explain why. And the directory does have files in it (tested on windows and mac). Any ideas?

library(shiny)
library(shinyFiles)


ui <- fluidPage(
  shinyFilesButton("Btn_GetFile", "Choose a file" ,
                   title = "Please select a file:", multiple = FALSE,
                   buttonType = "default", class = NULL),
  shinyDirButton('folder', 'Folder select', 'Please select a folder', FALSE),

  textOutput("txt_file")     
)


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

  volumes = getVolumes()
  observe({  
    shinyFileChoose(input, "Btn_GetFile", roots=volumes, session = session)

    if(!is.null(input$Btn_GetFile)){
      # browser()
      file_selected<-parseFilePaths(volumes, input$Btn_GetFile)
      output$txt_file <- renderText(as.character(file_selected$datapath))
    }
  })

  observe({  
    if(!is.null(input$Btn_Folder)){
      # browser()
      shinyDirChoose(input, 'folder', roots=volumes)
      dir <- reactive(input$folder)
      output$dir <- renderText(as.character(dir()))
    }
  })


}
shinyApp(ui = ui, server = server)

Upvotes: 3

Views: 1827

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84519

That's because you wrote Btn_Folder instead of folder here:

  observe({  
    if(!is.null(input$Btn_Folder)){
      shinyDirChoose(input, 'folder', roots=volumes)
      dir <- reactive(input$folder)
      output$dir <- renderText(as.character(dir()))
    }
  })

Replace with:

  observe({  
    if(!is.null(input$folder)){
      shinyDirChoose(input, 'folder', roots=volumes)
      dir <- reactive(input$folder)
      output$dir <- renderText(as.character(dir()))
    }
  })

As a side note, you don't need to define this reactive conductor inside the observer, simply do:

  observe({  
    if(!is.null(input$folder)){
      shinyDirChoose(input, 'folder', roots=volumes)
      output$dir <- renderText(as.character(input$folder))
    }
  })

Upvotes: 2

Related Questions