Shiny Directory selection

Hello,

I'm trying to create a directory upload selection as the one described in this post here.

It works quite well, but when navigating on the file system on my machine, the only directory available is the "Downloads":

image

By going "Home" I can't select any directory on the list.
...

Hi Nuno.Nogueira,
the problem is mostly the initial directory, you can specify it with the setwd()/getwd() which you specified here:

  global <- reactiveValues(datapath = getwd())

I would instead suggest this, way more simpler and gives more functionalityimo.:

library(shiny)
library(stringr)

ui <- fluidPage(
  mainPanel(
    fileInput("file",
              label = "", 
              multiple = TRUE,
              accept = c(".xlsx")
    )
  ))

server <- function(input, output) {
  observeEvent(input$file, {
    infile <- input$file
    if (is.null(infile)) {
      return(NULL)
    } else {
      numfiles <<- nrow(infile)
    }
    for (i in 1:numfiles) {
      if(str_detect(input$file$datapath[i], ".xlsx")){
        tryCatch(
          {
            Data <- read_excel(input$file$datapath[i], sheet = "") # specified what you want to import
            assign(paste("Data", i, sep = "_"), # gave unique name
                   Data,
                   envir = .GlobalEnv
            )
          },
          error = function(e) {}
        )
      }
    }
  })
}
# Run the application
shinyApp(ui = ui, server = server)

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Hi @Kerth92

Thanks a lot!
This is indeed simpler, but it is expecting a file as the input, and I need the user to select a directory instead (to be passed as a variable to the remaining script).

Yes, indeed. However, you can modify it. As you can see you can pull out the directory of the selected file with:

input$file$datapath[i]

and combine it with setwd() to select the directory. You can also save it as a variable for later use.
The loading .xlsx file was just an example.
Keep in mind that this will pass string looking like this ""C:\Users\kerth\AppData\Local\Temp\RtmpM3lf0r/ce50456e4c39ad7e7d4ac79a/0.xlsx"" so fo the directory you just need to detect the string and delete the filename. If you allow to select only one file then it can looks like this:

library(stringr)

ui <- fluidPage(
  mainPanel(
    fileInput("file",
              label = "", 
              multiple = FALSE,
              accept = c("")
    )
  ))

server <- function(input, output) {
  observeEvent(input$file, {
    infile <<- input$file$datapath
    
    if(str_detect(infile[1], ".jpg")){
      infile <<- gsub("0.jpg", "", infile)
    } else if ( str_detect(infile[1], ".xlsx")){
      infile <<- gsub("0.xlsx", "", infile)
    }
  })
}
# Run the application
shinyApp(ui = ui, server = server)