是否有与用于保存输出的 Shiny fileInput 函数等效的函数?

Is there an equivalent to the Shiny fileInput function for saving outputs?

Shiny 有一个不错的 fileInput() 功能,允许用户 浏览目录 和 select 将文件上传到应用程序。从 https://shiny.rstudio.com/reference/shiny/1.7.0/fileInput.html 中提取,这是 MWE:

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose CSV file to upload", accept = ".csv"),
      checkboxInput("header", "Header", TRUE)
    ),
    mainPanel(
      tableOutput("contents")
    )
  )
)
  
server <- function(input, output) {
  output$contents <- renderTable({
    file <- input$file1
    ext <- tools::file_ext(file$datapath)
      
    req(file)
    validate(need(ext == "csv", "Please upload a csv file"))
  
    read.csv(file$datapath, header = input$header)
  })
}
  
shinyApp(ui, server)

我在我的应用程序中使用它来检索数据,我真的很喜欢它。但是,我正在寻找一个类似的功能,用户可以通过浏览目录以选择保存文件的位置并 selecting 以类似的方式保存从 运行 应用程序生成的数据框一个文件名。关键是能够浏览本地目录。任何想法如何完成这个?最好是像 fileInput().

这样简单的方式

文件将是 .csv,但我也在考虑 .xls。

您可以在ui中使用downloadButton,在server中使用downloadHandler,如下所示:

library(shiny)

ui <- fluidPage(
        sidebarLayout(
                sidebarPanel(
                        fileInput("file1", "Choose CSV file to upload", accept = ".csv"),
                        checkboxInput("header", "Header", TRUE),
                        downloadButton("download")
                ),
                mainPanel(
                        tableOutput("contents"),
                )
        )
)

server <- function(input, output) {
        output$contents <- renderTable({
                file <- input$file1
                ext <- tools::file_ext(file$datapath)
                
                req(file)
                validate(need(ext == "csv", "Please upload a csv file"))
                
                read.csv(file$datapath, header = input$header)
        })
        
        output$download <- downloadHandler(
                filename = function() {
                        paste0(input$file1, ".csv")
                },
                content = function(file) {
                        write.csv(contents(), file)
                }
        )
}

shinyApp(ui, server)

这是一个非常基本的示例,它会在您单击操作按钮时调用 file.choose

library(shiny)

shinyApp(
  ui = 
    fluidPage(
      textInput(inputId = "txt_to_save", 
                label = "Enter text to save to a file"),
      actionButton(inputId = "btn_save_txt", 
                   label = "Save Text to File")
    ),
  
  server = 
    shinyServer(function(input, output, session){
      
      observeEvent(
        input$btn_save_txt, 
        {
          dest_file <- file.choose()
          write(input$txt_to_save, 
                dest_file)
        }
      )
      
    })
)

在实践中,如果你想要应用程序创建的文件名,但用户选择的目录,你也可以使用choose.dir()