RShiny:如何通过fileInput更新textAreaInput和文件内容?

时间:2017-06-15 16:30:25

标签: r shiny

我正在构建一个Shiny应用程序,该应用程序将使用1)文本区域字段中提供的默认内容来形成将由应用程序执行的查询或2)允许用户从文件中的文本上载查询,然后使用上传的内容(现在在textArea中)作为要执行的查询。除了我无法将文本文件加载到textAreaInput字段之外,所有部分都正常工作。我尝试过使用updateTextAreaInput。存在的例子很少,但我没有成功。

以下是一些成功允许用户选择文本文件的示例代码。选择后,文本文件的内容显示在" Debug"应用程序的一部分。如何使用updateTextAreaInput或其他方法将此内容放入textAreaInput(或textArea等其他可编辑文本字段)?注意我正在使用输出$ text而不是output $ query来进行测试......

建议非常感谢,工作代码示例更是如此!

library(shiny)

ui <- fluidPage(
    titlePanel("Load Text File into textAreaInput"),
    wellPanel(
        column(12, fileInput('fileRQ',   'Load Text File')),
        fluidRow(
            textAreaInput(inputId="query", "Text Content",rows=12, width='90%', 
         "# Default/example text. To be replaced by content of a file.")
        )
    ),
    fluidRow(
       tags$hr(),
       tags$h3("Debug"),
       verbatimTextOutput("text")    
    )
)

server <- function(input, output) {
    fileText <- eventReactive(input$fileRQ, {
        filePath <- input$fileRQ$datapath
        fileText <- paste(readLines(filePath), collapse = "\n")
        fileText
    })
    output$text <- fileText
}
shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

你太近了。只需在上传文件时更新textAreaInput :)请注意,如果您不需要文本,则可以使用oberveEvent代替eventReactive

library(shiny)

ui <- fluidPage(
  titlePanel("Load Text File into textAreaInput"),
  wellPanel(
    column(12, fileInput('fileRQ',   'Load Text File')),
    fluidRow(
      textAreaInput(inputId="query", "Text Content",rows=12, width='90%', 
                    "# Default/example text. To be replaced by content of a file.")
    )
  ),
  fluidRow(
    tags$hr(),
    tags$h3("Debug"),
    verbatimTextOutput("text")    
  )
)

server <- function(input, output, session) {

  # fileText() contains the recent file text
  fileText <- eventReactive(input$fileRQ, {
    filePath <- input$fileRQ$datapath
    fileText <- paste(readLines(filePath), collapse = "\n")

    # update text area with file content
    updateTextAreaInput(session, "query", value = fileText)

    # return the text to be displayed in text Outputs
    return(fileText)
  })

  output$text <- renderPrint({ fileText() })    
}
shinyApp(ui = ui, server = server)

enter image description here

相关问题