闪亮的应用运行代码生成pdf然后提供该pdf给用户下载

Tre*_*lof 6 r shiny

在我的闪亮应用程序中,我希望能够单击下载按钮,让它执行我在(在一个包中)在/ results文件夹中创建pdf的函数,然后将该创建的文件作为下载提供给闪亮的应用程序用户.我从下面的服务器粘贴了我当前的download_portfolio下载按钮代码(很多部分不确定如何使其可重现).想知道是否有人知道什么是错误的,我收到下面的错误消息,但是FUNCTION_TO_GENERATE_PDF_IN_/results()函数确实运行并创建了PDF,但随后应用程序重新加载,用户永远不会被提示下载.

我收到错误(但是我的函数仍然正确生成了pdf,只是应用程序重新加载,并且没有下载pdf的提议).

   Error in self$downloads$set(name, list(filename = filename, contentType = contentType,  : 
      argument "content" is missing, with no default
Run Code Online (Sandbox Code Playgroud)

app.R代码,我正在下载

observe({
  output$download_portfolio <- downloadHandler({
    FUNCTION_TO_GENERATE_PDF_IN_/results()
    filename = function() { paste(input$pdfname) }
    content = function(file) {
      file.copy(paste("results/",input$pdfname, file, overwrite = TRUE)
    } 
  })
  })
Run Code Online (Sandbox Code Playgroud)

bub*_*ble 4

您使用的方法downloadHandler不正确。这里不需要observe()- 函数,因为闪亮提供了“反应性”,这意味着您可以将对象绑定到 ui 元素,只要对象发生变化,这些元素就会更新。因此,您只需downloadHandler为您的下载按钮分配 a 并告诉它如何生成您想要提供的文件:

library(shiny)

ui <- fluidPage( # just the download-button and a textInput for the filename
  textInput("pdfname", "Filename", "My.pdf"),
  downloadButton("outputButton", "Download PDF")
  )

server <- function(session, input, output) {
  # No need for an observer! Just assign the downloadHandler to the button.
  output$outputButton <- downloadHandler(input$pdfname, function(theFile) {
    # The first parameter is the name given to the file provided for download to the user.
    # The parameter in the function (theFile) is a placeholder for the name that is later
    # assigned to the download-file. 

    # Now you can call your pdf-generating function...
    makePdf()

    # ... and use file.copy to provide the file "in" the save-button
    file.copy(from = "/results/myGenerated.pdf", to = theFile)
  })
}

# Sample pdf-generating function:
makePdf <- function(){
  pdf(file = "/results/myGenerated.pdf")
  plot(cars)
  dev.off()
}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

但是,您不需要先存储文件,您可能想直接将它们保存在“下载”按钮中:

library(shiny)

ui <- fluidPage( # As above
  textInput("pdfname", "Filename", "My.pdf"),
  downloadButton("outputButton", "Download PDF")
  )

server <- function(input, output) {
  output$outputButton <- downloadHandler(input$pdfname, function(theFile) {
    # Here, your pdf-generator is provided with the "filename" that is used
    # to provide the file for the user.
    makePdf(theFile)
  })
}

# Sample pdf-generating function:
makePdf <- function(filename){
  pdf(file = filename)
  plot(cars)
  dev.off()
}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)