如何在一个闪亮的模块中使用downloadButton和downloadHandler?

svmlkihl  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(108)

我试图建立一个闪亮的模块,我可以用来下载不同的文件从一个闪亮的应用程序。但downloadButton是不是工作,因为我希望他们。它是响应一个html文件,这不是我想要的。以下是我的代码:

library(shiny)

downloadUI <- function(id, label){
  ns <- NS(id)
  
  actionButton(
    inputId = ns("action"),
    label = label,
    icon = icon("download")
  )
}

downloadServer <- function(id, filename){
  moduleServer(
    id,
    function(input, output, session){
      observeEvent(
        input$action,
        {
          showModal(
            modalDialog(
              title = NULL,
              h3("Download the file?", style = "text-align: center;"),
              footer = tagList(
                downloadButton(
                  outputId = "download",
                  label = "Yes"
                ),
                modalButton("Cancel")
              ),
              size = "m"
            )
          )
        }
      )
      
      output$download <- downloadHandler(
        filename = paste0(filename, ".csv"),
        content = function(file){
          write.csv(iris, file = file, row.names = FALSE)
        }
      )
    }
  )
}

ui <- fluidPage(
  downloadUI("irisDownload", label = "Download Iris data")
)

server <- function(input, output, session) {
  downloadServer("irisDownload", filename = "iris")
}

shinyApp(ui, server)

有人能帮我弄明白我做错了什么吗?

wsxa1bj1

wsxa1bj11#

您只需要在服务器端为downloadButton提供一个名称空间ns

library(shiny)

downloadUI <- function(id, label){
  ns <- NS(id)
  
  actionButton(
    inputId = ns("action"),
    label = label,
    icon = icon("download")
  )
}

downloadServer <- function(id, filename){
  moduleServer(
    id,
    function(input, output, session){
      ns <- session$ns
      observeEvent(
        input$action,
        {
          showModal(
            modalDialog(
              title = NULL,
              h3("Download the file?", style = "text-align: center;"),
              footer = tagList(
                downloadButton(
                  outputId = ns("download"),
                  label = "Yes"
                ),
                modalButton("Cancel")
              ),
              size = "m"
            )
          )
        }
      )
      
      output$download <- downloadHandler(
        filename = paste0(filename, ".csv"),
        content = function(file){
          write.csv(iris, file = file, row.names = FALSE)
        }
      )
    }
  )
}

ui <- fluidPage(
  downloadUI("irisDownload", label = "Download Iris data")
)

server <- function(input, output, session) {
  downloadServer("irisDownload", filename = "iris")
}

shinyApp(ui, server)

相关问题