Resetting fileInput in Shiny App

你说的曾经没有我的故事 提交于 2020-01-04 11:10:41

问题


I have been trying for a long time to reset fileInput in a Shiny app and read solutions to similar problems, but my problem still persists. Most solutions ultimately lead to using Dean Attali's brilliant shinyjs package and the reset() function therein. Here's what my code looks like after following these instructions:

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)

I initially select the csv option and am able to load a csv file. Now when I press the reset button, it clears the data. As soon as I select the xls option, I get an error:

Listening on http://127.0.0.1:4135
Warning: Error in : Unknown file extension: csv

Which makes me believe that input$inFile$datapath still contains the pathname of the csv file that I selected earlier. I have run out of ideas on how to solve this problem and would greatly appreciate some help please.


回答1:


Ideally fileInput would properly reset, but you can do this as a workaround. Add an explicit flag variable (rv$clear) to indicate whether you're in cleared state, and toggle that on and off in high-priority observers when reset and upload occur, respectively.

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)


来源:https://stackoverflow.com/questions/49344468/resetting-fileinput-in-shiny-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!