关于这个问题已经有类似的帖子了(例如,如何更新闪亮的fileInput对象?),但我仍然无法弄清楚人们如何强制Shiny忘记使用widget input$file之后的值fileInput.
当一个人想要触发上传文件actionButton("Submit"在我的情况下调用)然后用另一个actionButton("Reset"这里)重置其值时,问题变得唠叨.再次单击"提交"按钮时,很明显输入的$ file值仍然存在.
我尝试使用一些推荐的解决方案:shinyjs包装和刷新fileInput模块带renderUI/ uiOutput- 但仍然没有结果.
这是我的代码:
server.R
shinyServer(function(input, output, session) {
values <- reactiveValues(
file = NULL
)
observeEvent(input$submit, {
values$file <- input$file1
})
observeEvent(input$reset, {
values$file <- NULL
output$resettableInput <- renderUI({
fileInput('file1', label = NULL)
})
}, ignoreNULL = F)
output$summary <- renderText({
return(paste('Uploaded file:', values$file$name))
})
})
Run Code Online (Sandbox Code Playgroud)
ui.R
shinyUI(bootstrapPage(
headerPanel('Reset / Submit file input example'),
sidebarPanel(
uiOutput('resettableInput'),
fluidRow(
column(4,
actionButton('reset', 'Reset All')
),
column(4,
actionButton('submit', 'Submit')
)
)
),
mainPanel(
h4('Summary'),
verbatimTextOutput('summary')
)
))
Run Code Online (Sandbox Code Playgroud)
我将不胜感激任何帮助.
input$file1 由Shiny缓存,因此在下次上传之前不会更改.
由于您需要一个文件名变量,该变量input$file1$name在大多数时间映射但重置NULL为单击重置按钮时,您需要创建另一个层并维护此关系.
您可以创建变量upload_state,将其设置为uploaded使用文件上载事件,并reset使用重置按钮.
使用一个反应式表达式,它将采用input$file1$name或NULL根据upload_state值.
不需要submit按钮.
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)
Run Code Online (Sandbox Code Playgroud)
我知道这是一篇旧帖子,但您可以通过在服务器中从头开始重建来重置输入。
在 ui.R 中,您可以输入:
...
uiOutput('file1_ui') ## instead of fileInput('file1', label = NULL)
...
Run Code Online (Sandbox Code Playgroud)
在 server.R 中添加:
...
output$file1_ui <- renderUI({
input$reset ## Create a dependency with the reset button
fileInput('file1', label = NULL)
})
...
Run Code Online (Sandbox Code Playgroud)