52

Let's say I have an existing zip file (out.zip) in my shiny app (i.e. located on a server). 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.

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)
Community
  • 1
  • 1
cdeterman
  • 19,630
  • 7
  • 76
  • 100

2 Answers2

77

After poking around with different file handling functions I discovered that file.copy can be used to download the file.

I change downloadHandler to:

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

  content <- function(file) {
    file.copy("out.zip", file)
  },
  contentType = "application/zip"
)
cdeterman
  • 19,630
  • 7
  • 76
  • 100
  • 2
    Where does your zipped file live? Inside www folder or can it be in any folder? – zx8754 Mar 11 '18 at 21:20
  • 3
    @zx8754 it should be any folder you specify. You would just need to provide the path to where you want it saved. – cdeterman Mar 12 '18 at 14:46
  • 1
    Thank you. To clarify, "out.zip" is the file that exists in one of my app folders, right? – zx8754 Mar 12 '18 at 14:48
  • 5
    Does this solution works locally for instance when running Shiny through R Studio or only in a production environment? In my case the HTML of the page is downloaded instead – gkoul Feb 05 '20 at 19:43
25

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:

|
|- 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

e.g. to use within your Shiny ui:

# in ui somewhere
...
  a(href="downloadme.csv", "Download CSV", download=NA, target="_blank")
...
MarkeD
  • 2,500
  • 2
  • 21
  • 35