简体   繁体   English

R Shiny:下载现有文件

[英]R Shiny: Download existing file

Let's say I have an existing zip file ( out.zip ) in my shiny app (ie located on a server).假设我的闪亮应用程序中有一个现有的 zip 文件 ( out.zip )(即位于服务器上)。 I would like to have the user be able to download this file.我想让用户能够下载这个文件。 This question is very similar to this one .这个问题很相似, 这一个 However, that question zips files within the downloadHandler whereas the zip file already exists in my case.但是,该问题在downloadHandler中压缩文件,而在我的情况下该 zip 文件已经存在。

library(shiny)

app <- list(
  ui = fluidPage(
    titlePanel(""),
    sidebarLayout(
      sidebarPanel(
        downloadButton("downloadData", label = "Download")
      ),
      mainPanel(h6("Sample download", align = "center"))
    )
  ),

  server = function(input, output) {  
    output$downloadData <- downloadHandler(
      filename <- function() {
        paste("output", "zip", sep=".")
      },

      content <- function(file) {
        # not sure what to put here???
      },
      contentType = "application/zip"
    )
  }
)

shiny::runApp(app)

After poking around with different file handling functions I discovered that file.copy can be used to download the file.在研究了不同的文件处理函数后,我发现file.copy可用于下载文件。

I change downloadHandler to:我将downloadHandler更改为:

output$downloadData <- downloadHandler(
  filename <- function() {
    paste("output", "zip", sep=".")
  },

  content <- function(file) {
    file.copy("out.zip", file)
  },
  contentType = "application/zip"
)

A few years later, but I think there is a simpler way if you do not need dynamic file generation by placing the file in the www/ folder of the Shiny app:几年后,但我认为如果您不需要动态文件生成,则有一种更简单的方法,将文件放在 Shiny 应用程序的www/文件夹中:

|
|- app.R
|- www/
       - downloadme.csv

Then when your Shiny app is live the file is available at shiny-url.com/downloadme.csv - or when testing locally 127.0.0.1:1221/downloadme.csv然后,当您的 Shiny 应用程序上线时,该文件可在shiny-url.com/downloadme.csv - 或在本地测试时127.0.0.1:1221/downloadme.csv

eg to use within your Shiny ui:例如在你的 Shiny ui 中使用:

# in ui somewhere
...
  a(href="downloadme.csv", "Download CSV", download=NA, target="_blank")
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM