R 自动开始下载

R 自动开始下载,r,shiny,R,Shiny,我想在按下按钮时初始化R中的文件下载,并在生成文件之前进行一些检查 我用下载处理器()愚弄了arround。但是我想捕捉另一个按钮的事件,做一些事情并检查数据,当一切顺利时,生成文件并初始化下载,而不必按downloadHandler中的download按钮 目前,我已经在downloadHandler中实现了大多数检查,但是当一些检查没有完成时,它会生成一个失败的下载。我不喜欢这种行为 output$downloadData <- downloadHandler( filename

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

我用下载处理器()愚弄了arround。但是我想捕捉另一个按钮的事件,做一些事情并检查数据,当一切顺利时,生成文件并初始化下载,而不必按downloadHandler中的download按钮

目前,我已经在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)

    })

  }
)

output$downloadData详细说明我的评论,一个简单的例子:

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)
库(闪亮)
图书馆(shinyjs)
#检查数据的功能;返回TRUE或FALSE

checkData您可以隐藏下载按钮并使用
shinyjs::runjs(“$”(“#downloadData”)[0]触发下载。单击()”
。谢谢!这正是我想要的!