有条件的 fileInput 上传器来计算 Shiny 中的文件数量

Conditional fileInput uploader to count number of files in Shiny

我有以下闪亮的应用程序

require(shiny)

ui <- fluidPage(  
  numericInput("num", "num:", 10, min = 1, max = 100),
  fileInput(inputId = "upl", multiple = T, label = "upl")
)

server <- function(input, output) { 

}

shinyApp(ui, server)

我希望 fileInput 上传者只上传 numericInput 中指定的文件数量。否则它应该给出文件数量错误的消息。

我尝试为此使用 shinyjs

//remove existing listener
document.getElementById('upl').outerHTML = document.getElementById('upl').outerHTML;
document.getElementById('upl').addEventListener('change', function() { 
  if(document.getElementById('upl').files.length == document.getElementById('num').value) {
    // something that uploads the files
    // I tried to copy the function from the already existing listener, but its anonymous and has no reference so its impossible to copy
  } else {
     alert('wrong number of files');
  } 
})

我还没有找到一种方法来根据条件停止或启动上传,因为 input 元素上已经有一个事件侦听器,带有我无法复制的匿名函数。

可能有一种我不知道的更简单的方法,知道如何在 shiny 中构建条件上传器吗?

这似乎有效:

library(shiny)
library(shinyjs)

js <- "
$(document).ready(function(){
document.getElementById('upl').addEventListener('change', function() { 
  if(document.getElementById('upl').files.length == document.getElementById('num').value) {
    return true;
  } else {
    alert('wrong number of files');
    this.value = '';
    return false;
  } 
})
})"

ui <- fluidPage(
  useShinyjs(),
  tags$head(tags$script(HTML(js))),
  numericInput("num", "num:", 2, min = 1, max = 100),
  fileInput(inputId = "upl", multiple = T, label = "upl")
)

server <- function(input, output) { }

shinyApp(ui, server)