如何在Shiny的服务器功能中包含指向本地文件的HTML下载链接?

时间:2019-06-13 18:40:47

标签: html r shiny

我有一个应用程序,从本质上讲,它需要具有链接才能下载几个本地存储在www文件夹中的不同PDF。我已经能够弄清楚如何在UI.R文件中生成此链接,但是我需要在服务器中执行此操作,并且在HTML方面有些挣扎。

在UI文件中,我只使用一个简单的

tags$a(href='Incarceration rate graph.pdf', target='blank', 'Incarceration', download = 'Incarceration rate graph.pdf')

,这将下载所需的文件。但是,我尝试使用以下最小应用程序在服务器功能中复制此代码

library(shiny)

setwd("//ace/home/anambiar/PDF download test")

ui <- fluidPage(
htmlOutput("test1")
)


server <- function(input, output, session) {
output$test1 <- renderUI({
  HTML("<a href='Incarceration rate graph.pdf' target = 'blank' download='Incarceration rate graph.pdf'> Incarceration rate </a>")
})
}

shinyApp(ui = ui, server = server)

使用此应用程序,即使通过inspect元素的实际HTML看上去几乎完全一样,我在下载时也会看到一条错误消息:“失败-没有文件”。

2 个答案:

答案 0 :(得分:0)

library(shiny)


ui <- fluidPage(
  tags$h1("Test"),
  downloadLink('downloadData', 'Download'),
  selectizeInput("files", "Select Files", choices = c("File A", "File B", "File C"), selected = "File A", multiple = FALSE)
)


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

  output$downloadData <- downloadHandler(
    filename = function() {
      paste('data-', input$files, "-", Sys.Date(), '.pdf', sep='')
    },
    content = function(file) {
      file.copy(paste0(input$files, ".pdf"), file)
    }
  )



}

shinyApp(ui = ui, server = server)

这是下载数据的动态方法。

答案 1 :(得分:0)

如果要生成50个链接,建议您查看Modularizing Shiny app codeHere是另一个不错的链接,它说明了如何使用purrr从矢量开始生成多个UI元素(在您的情况下为downloadLink)(请参见“优化模块的部署”一节)。 / p>