`I want a user to select a file. However, the path and file name are not what I expected.
library(shiny)
ui <- fluidPage(
fileInput("folder", "Find One File In A Folder Of Data Files:", multiple = FALSE),
actionButton("submit", "Submit")
)
server <- function(input, output, session) {
# Reactive values to store user inputs
user_inputs <- reactiveValues(text1 = NULL)
observeEvent(input$submit, {
# Get user inputs
user_inputs$text1 <- (input$folder$datapath)
# Stop the Shiny app
stopApp()
})
# Access reactive values
observe({
req(user_inputs$text1)
# Print user inputs
print(paste("Text 1:", user_inputs$text1))
})
}
# Run the Shiny app
shinyApp(ui, server)
The expected path and desired result is:
"C:\Users\tebert\OneDrive - University of Florida\Work\A New EPG Folder\EPG 2024 SAS\Aphid Data\Control 2.ANA"
What I get is:
"Text 1: C:\Users\tebert\AppData\Local\Temp\RtmpgPDbBx/2e91f4b2ae83bac6e20ac214/0.ANA"
I used ChatGPT to find a solution. It came with a warning that it might not work on all platforms due to security issues. It does give me the correct file name which is important because treatments are coded into the file name. It does not give me the right path. The intent is that others can use this code, so potentially failing to run on other systems is a problem.
ui <- fluidPage(
tags$head(
tags$script("
$(document).on('change', '#folder', function(event) {
var filePath = $(this).val();
Shiny.setInputValue('file_path', filePath);
});
")
),
fileInput("folder", "Find One File In A Folder Of Data Files:", multiple = FALSE),
actionButton("submit", "Submit")
)
server <- function(input, output, session) {
observeEvent(input$file_path, {
# Get the file path
file_path <- input$file_path
# Get the directory path and file name
directory_path <- dirname(file_path)
file_name <- basename(file_path)
# Print the directory path and file name
print(paste("Original Directory Path:", directory_path))
print(paste("File Name:", file_name))
# Stop the Shiny app
stopApp()
})
}
# Run the Shiny app
shinyApp(ui, server)
this is a security feature since no webpage (what shiny essential is - a very nice web page) should have access to your local files. So shiny uploads the selected file and stores it on the server (in this case the temp folder of your windows machine) - hence the temp file path that you see.
If you want to mitigate that and make your files available directly you will run into security issues because your code will bee seen as malware since it accesses resources it should not be allowed to.