Get startedGet started for free

Upload a text file (server)

After the user selects a file, that file gets uploaded to the computer that runs the Shiny app, and it becomes available in the server.

If the input ID of a file input is "myfile", then you might expect input$myfile to give you access to the file that was uploaded, but that is not how file inputs actually work. input$myfile will return a data.frame that contains a few pieces of metadata about the selected file, with the main one to care about being datapath. Assuming the file input's ID is "myfile", input$myfile$datapath will be the path where the file is located.

After getting the uploaded file's path (for example C:\Users\Dean\AppData\Local\Temp\path\to\file.txt), this path can be used to read the file in whatever way you need. You may use read.csv() if the uploaded file is a CSV file, or readLines() if you simply want to read all the lines in the file, or any other function that accepts a file path.

This exercise is part of the course

Case Studies: Building Web Applications with Shiny in R

View Course

Exercise instructions

Your task is to use the text from the uploaded file as the data source for the word cloud. Specifically:

  • Define a reactive variable named input_file that will hold the text from the uploaded file (line 19).
    • Using the uploaded file's path, read the text in the uploaded file with the readLines() function (line 24).
  • Use the input_file() reactive variable as the data parameter of the word cloud function (line 29).

To test the file upload, you can create any text file on your computer and upload it to the app. Alternatively, you can use this file (save it as a text file on your computer) to test the word cloud function with the text from Martin Luther King Jr's I Have a Dream speech.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

ui <- fluidPage(
  h1("Word Cloud"),
  sidebarLayout(
    sidebarPanel(
      textAreaInput("text", "Enter text", rows = 7),
      fileInput("file", "Select a file"),
      numericInput("num", "Maximum number of words",
                   value = 100, min = 5),
      colourInput("col", "Background color", value = "white")
    ),
    mainPanel(
      wordcloud2Output("cloud")
    )
  )
)

server <- function(input, output) {
  # Define a reactive variable named `input_file`
  input_file <- ___({
    if (is.null(input$file)) {
      return("")
    }
    # Read the text in the uploaded file
    readLines(input$___$datapath)
  })

  output$cloud <- renderWordcloud2({
    # Use the reactive variable as the word cloud data source
    create_wordcloud(data = ___(), num_words = input$num,
                     background = input$col)
  })
}

shinyApp(ui = ui, server = server)
Edit and Run Code