How to reset a value of fileInput in Shiny?

前端 未结 2 1308
盖世英雄少女心
盖世英雄少女心 2021-02-15 10:50

There are already similar posts on this matter (ex. how can I update a shiny fileInput object?), but I still cannot figure out how one may force Shiny to forget a value of

相关标签:
2条回答
  • 2021-02-15 11:36

    input$file1 is cached by Shiny so will not change before next upload.

    Since you want a file name variable which map to input$file1$name in most time but reset to NULL when reset button is clicked, you need to create another layer and maintain this relationship.

    • You can create a variable upload_state, set it to uploaded with file upload event, and reset with reset button.

    • use a reactive expression which will take input$file1$name or NULL according to upload_state value.

    There is no need for the submit button.

    library(shiny)
    ui <- shinyUI(bootstrapPage(
      headerPanel("Reset / Submit file input example"),
      sidebarPanel(
        fileInput('file1', label = NULL),
        fluidRow(
          column(4,
                 actionButton('reset', 'Reset Input')
          ))
      ),
    
      mainPanel(
        h4("Summary"),
        verbatimTextOutput("summary")
      )
    ))
    
    server <- shinyServer(function(input, output, session) {
      values <- reactiveValues(
        upload_state = NULL
      )
    
      observeEvent(input$file1, {
        values$upload_state <- 'uploaded'
      })
    
      observeEvent(input$reset, {
        values$upload_state <- 'reset'
      })
    
      file_input <- reactive({
        if (is.null(values$upload_state)) {
          return(NULL)
        } else if (values$upload_state == 'uploaded') {
          return(input$file1)
        } else if (values$upload_state == 'reset') {
          return(NULL)
        }
      })
    
      output$summary <- renderText({
        return(paste("Uploaded file:", file_input()$name))
      })
    })
    
    shinyApp(ui = ui, server = server)
    
    0 讨论(0)
  • 2021-02-15 11:52

    I know this is an old post, but you can reset the input by rebuilding it from scratch in the server.

    In ui.R you can put:

    ...
    uiOutput('file1_ui') ## instead of fileInput('file1', label = NULL)
    ...
    

    And in server.R add this:

    ...
    output$file1_ui <- renderUI({
      input$reset ## Create a dependency with the reset button
      fileInput('file1', label = NULL)
    })
    ...
    
    0 讨论(0)
提交回复
热议问题