R Shiny自动开始下载

时间:2019-02-12 14:30:53

标签: r shiny

我想在按下按钮时初始化R Shiny中文件的下载,并在生成文件之前进行一些检查。

我欺骗了downloadHandler(https://shiny.rstudio.com/gallery/file-download.html)。但是我想捕捉另一个按钮的事件,执行一些操作并检查数据,当一切顺利时,生成文件并初始化下载,而无需按下downloadHandler的下载按钮。

我现在已经在downloadHandler中实现了大多数检查,但是当某些检查没有得到满足时,它现在会生成下载失败。我不喜欢这种行为。

output$downloadData <- downloadHandler(
  filename = function() { paste("DATA_EXPORT-", Sys.Date(), ".csv", sep="") 
},
  content = function(file) {
    withProgress(message = 'Export data', value = 0, {
    # Number of steps
    n <- 3

    incProgress(1/n, detail = "Pre checks and get data")

    # checks if inputs for get_data are well defined

    dataSet <- get_data(blabla)

    incProgress(1/n, detail = "Post Proces and check")



    incProgress(1/n, detail = "generate flatfile")
    write.csv(dataSet, file, row.names = FALSE)

    })

  }
)

1 个答案:

答案 0 :(得分:1)

为了详细说明我的评论,请举一个最小的例子:

library(shiny)
library(shinyjs)

# function which checks the data; returns TRUE or FALSE
checkData <- function(dat){
  TRUE
}

# function which transforms the data; returns NULL if check not TRUE
processData <- function(dat){
  if(checkData(dat)){
    # do something with dat
    names(dat) <- toupper(names(dat)) # for our example
    return(dat)
  }else{
    return(NULL)
  }
}

ui <- fluidPage(
  useShinyjs(),
  conditionalPanel(
    "false", # always hide the download button
    downloadButton("downloadData")
  ),
  actionButton("check", "Download")
)

server <- function(input, output, session){

  dat <- mtcars

  finalData <- reactiveVal() # to store the processed data
  observeEvent(input$check, {
    if(!is.null(df <- processData(dat))){
      finalData(df)
      runjs("$('#downloadData')[0].click();")
    }else{
      # something which throws an alert message "invalid data" 
      # (eg with shinyBS::createAlert or shinyWidgets::sendSweetAlert)
    }
  })

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

shinyApp(ui, server)