【问题标题】:Conditional fileInput uploader to count number of files in Shiny有条件的 fileInput 上传器来计算 Shiny 中的文件数
【发布时间】:2019-01-04 13:23:01
【问题描述】:

我有以下闪亮的应用程序

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 元素上已经有一个事件监听器,它带有一个我无法复制的匿名函数。

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

【问题讨论】:

    标签: r shiny shinyjs


    【解决方案1】:

    这似乎有效:

    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)
    

    【讨论】:

    • 您能解释一下this.value = ''; 的作用吗? (代码工作顺便说一句)
    • @MehdiNellen thisupl 元素,this.value = '' 重置它的值(它的值是上传文件的名称)
    猜你喜欢
    • 2018-04-13
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 2016-11-16
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多