Условный загрузчик fileInput для подсчета количества файлов в Shiny - PullRequest
0 голосов
/ 04 января 2019

У меня есть следующее блестящее приложение

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 уже имеет прослушиватель событий с анонимной функцией, которую я не могу скопировать.

Может быть, есть более простой способ, о котором я не знаю, есть идеи, как создать условный загрузчик в блестящем?

1 Ответ

0 голосов
/ 05 января 2019

Это похоже на работу:

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)
...