`downloadHandler`:下载失败(无数据)时如何正常退出?

时间:2020-02-20 21:30:25

标签: r shiny

我有一个downloadButton和一个downloadHandler,当我们要下载数据时,我必须运行一个程序来确定是否有要下载的数据。

我找不到取消下载处理程序的方法,下面的应用程序提示我们保存一些垃圾HTML文件。

我们怎样才能使downloadHandler出口整洁?

library(shiny)

ui <- fluidPage(

  downloadButton("btn", "Download")
)

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

  output$btn <- downloadHandler(
    filename = function(){
      "out.txt"
    },
    content = function(file){

# this example always fails.
      if(TRUE){
        print("Sorry, data not written.")
        return(NULL)
      } else {
        writeLines(mtcars, "out.txt")
      }

    }

  )

}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:2)

AFAIK,一旦按下按钮就无法取消下载。

这是一种无需使用downloadHandler即可下载文件的方法。它包含创建一个a元素,一旦按下按钮,您要下载的文件将转换为base64编码,并借助shinyjs::runjs将base64字符串提供给{{ href元素的1}}属性,并触发对a元素的单击。

a