上傳文字檔(server)
在使用者選擇檔案後,該檔案會上傳到執行 Shiny 應用程式的電腦上,並可在伺服器端取得。
如果檔案輸入元件的 input ID 是「myfile」,你可能直覺會以為 input$myfile 能直接取得上傳的檔案,但檔案輸入其實不是這樣運作的。input$myfile 會回傳一個 data.frame,裡面包含所選檔案的一些中介資訊(metadata),其中最重要的是 datapath。在檔案輸入的 ID 為「myfile」的情況下,input$myfile$datapath 會是該檔案所在的位置路徑。
在取得上傳檔案的路徑之後(例如 C:\Users\Dean\AppData\Local\Temp\path\to\file.txt),你就能用這個路徑以任何需要的方式讀取檔案。若上傳的是 CSV 檔,可以用 read.csv();若只是想讀取檔案中的每一行,則可用 readLines();或使用任何接受檔案路徑作為輸入的其他函式。
本練習屬於課程
案例研究:使用 R 的 Shiny 建置網頁應用程式
練習說明
你的任務是將上傳檔案中的文字作為文字雲的資料來源。具體來說:
- 定義一個名為
input_file的 reactive 變數,用來存放上傳檔案的文字(第 19 行)。- 使用上傳檔案的路徑,透過
readLines()函式讀取上傳檔案中的文字(第 24 行)。
- 使用上傳檔案的路徑,透過
- 將
input_file()這個 reactive 變數作為文字雲函式的data參數(第 29 行)。
若要測試檔案上傳功能,你可以在自己的電腦上建立任意文字檔並上傳到應用程式。或者,你也可以使用「this file」(先下載並在電腦上另存為文字檔),以馬丁·路德·金恩的演說《I Have a Dream》的文字來測試文字雲功能。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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)