在 Shiny App 中重置 fileInput

标签 r shiny shinyjs

我已经尝试了很长时间重置fileInput在 Shiny 应用程序中并阅读类似问题的解决方案,但我的问题仍然存在。大多数解决方案最终导致使用 Dean Attali 的精彩shinyjs包和reset()其中的功能。这是我遵循 these 后的代码的样子指示:

library(shiny)
library(shinyjs) 
library(xlsx) 
library(tidyverse) 

ui <- fluidPage(
  useShinyjs(),
  fileInput('inFile', 'Choose file'),
  actionButton('reset', 'Reset'),
  radioButtons("type","Choose file type",choices = c('csv','xls')),
  tableOutput('tbl')
)

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

  rv <- reactiveValues(data = NULL)

  observe({
    req(input$inFile)
    if(input$type=='csv'){
      rv$data <- read.csv(input$inFile$datapath)
    }
    if(input$type=='xls'){
      rv$data <- read_excel(input$inFile$datapath)
    }

  })

  observeEvent(input$reset, {
    rv$data <- NULL
    reset('inFile')
  })

  output$tbl <- renderTable({
    rv$data
  })
}

shinyApp(ui, server)

我最初选择了csv选项并且能够加载一个 csv 文件。现在,当我按下重置按钮时,它会清除数据。一旦我选择了xls选项,我收到一个错误:
Listening on http://127.0.0.1:4135
Warning: Error in : Unknown file extension: csv

这让我相信 input$inFile$datapath仍然包含我之前选择的 csv 文件的路径名。我已经没有关于如何解决这个问题的想法,非常感谢您的帮助。

最佳答案

理想情况下 fileInput会正确重置,但您可以将此作为解决方法。添加一个显式标志变量 ( rv$clear ) 以指示您是否处于清除状态,并分别在发生重置和上传时在高优先级观察者中打开和关闭该状态。

library(shiny)
library(shinyjs) 
library(xlsx) 
library(tidyverse) 

ui <- fluidPage(
  useShinyjs(),
  fileInput('inFile', 'Choose file'),
  actionButton('reset', 'Reset'),
  radioButtons("type","Choose file type",choices = c('csv','xls')),
  tableOutput('tbl')
)

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

  rv <- reactiveValues(
    data = NULL,
    clear = FALSE
  )

  observe({
    req(input$inFile)
    req(!rv$clear)

    if(input$type=='csv'){
      rv$data <- read.csv(input$inFile$datapath)
    }
    if(input$type=='xls'){
      rv$data <- read_excel(input$inFile$datapath)
    }

  })

  observeEvent(input$inFile, {
    rv$clear <- FALSE
  }, priority = 1000)

  observeEvent(input$reset, {
    rv$data <- NULL
    rv$clear <- TRUE
    reset('inFile')
  }, priority = 1000)

  output$tbl <- renderTable({
    rv$data
  })
}

shinyApp(ui, server)

关于在 Shiny App 中重置 fileInput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49344468/

相关文章:

IE10 上的 R Shiny 页面

user-interface - 单击 Shiny 的操作按钮转到 flexdashboard 的另一页

R shiny - Shiny 模块函数中最后单击的按钮 id

r - 将字符串变量分割成多个变量

python - Rpy2 完全支持 ggplot2.layer 吗?

R Shiny 错误 : "Object of Type Closer is not Subsettable"

r - 嵌套 callModules 的 Shiny 命名空间问题

r - lm() 函数中的子集参数如何工作?

r - 在 R 中创建一个包含两个变量的 "by"循环

在 Shiny 启动时跨选项卡呈现传单标记