Sven
Sven

Reputation: 83

get() the name of an uploaded file in shiny

I have a simple question regarding my snippet of code below.

library(shiny)
ui <- fluidPage(

  fileInput("x", "upload file", accept = c(
    "text/csv",
    "text/comma-seperated-values, text/plain",
    ".csv")),

  tableOutput("my_csv")
)

server <- function(input, output) {


  csv <- reactive({
    inFile <- input$x
    if (is.null(inFile))
      return(NULL)
    df<- read.csv2(inFile$datapath, header=T)
    return(df)
  })

  output$my_csv <- renderTable({
    validate(need(!is.null(csv()),'no file yet.'))
      csv()
  })
}


shinyApp(ui, server)

What I want is a function like get() to print the name of the uploaded csv-file. In the next step I want to create a list (named "list") with the uploaded file as its first object with the file's name. So, if the uploaded file's name is "squirrel.csv" and I call list$squirrel.csv I want to see the table.

Upvotes: 3

Views: 2765

Answers (1)

pogibas
pogibas

Reputation: 28369

You have to extract basename from the name field in input$x (x because your inputId is called x).

Add this to server part:

output$my_csv_name <- renderText({
  # Test if file is selected
  if (!is.null(input$x$datapath)) {
      # Extract file name (additionally remove file extension using sub)
      return(sub(".csv$", "", basename(input$x$name)))
  } else {
      return(NULL)
  }
})

To ui part add following line to display file name:

textOutput("my_csv_name")

Upvotes: 10

Related Questions