简体   繁体   English

如何使用变量contentType实现R Shiny downloadHandler?

[英]How to implement R Shiny downloadHandler with variable contentType?

As per the docs , the downloadHandler should accept contentType as a string. 根据docs ,downloadHandler应该接受contentType作为字符串。 Since the contentType is not a constant, I am trying to pass a variable or reactive. 由于contentType不是常量,因此我尝试传递变量或反应式。 But the app fails whenever the contentType is not strictly a string. 但是,只要contentType严格不是字符串,应用程序就会失败。 How could I pass a variable value? 如何传递变量值?

I have tried function(){} , reactive , eventReactive . 我试图function(){} reactiveeventReactive What confuses me is that it works just fine for filename = function(){} . 令我感到困惑的是,它对于filename = function(){}

ui <- fluidPage(
  downloadLink("downloadData", "Download")
)

server <- function(input, output) {
  # Our dataset
  data <- mtcars

  output$downloadData <- downloadHandler(
    filename = function() {
      paste("data-", Sys.Date(), ".csv", sep="")
    },
    content = function(file) {
      write.csv(data, file)
    },
    contentType = function() {
      "text/csv"
    }
  )
}

shinyApp(ui, server)

In this case, the error message is is.na() applied to non-(list or vector) of type 'closure' and the file is not downloaded correctly ( server error ). 在这种情况下,错误消息is.na() applied to non-(list or vector) of type 'closure'并且文件未正确下载( server error )。

ui <- fluidPage(
    radioButtons("csvs", label = "Type to download", choices = c(".txt", ".csv"), selected = ".csv"),
    downloadLink("downloadData", "Download")
)

server <- function(input, output) {
    # Our dataset
    data <- mtcars

    output$downloadData <- downloadHandler(
        filename = function() {
            paste("data-", Sys.Date(), input$csvs, sep="")
        },
        content = function(file) {
            write.csv(data, file)
        }
    )
}

shinyApp(ui, server)

An easier and working way is to let the user pick it with a radioButton 一种更简单有效的方法是让用户使用radioButton选择它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM