R – Shiny: download zip archive

rshiny

I can't make shiny's downloadHandler to output the zip file:

# server.R
library(shiny)

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

    content <- function(fname) {
      fs <- c()
      tmpdir <- tempdir()
      setwd(tempdir())
      for (i in c(1,2,3,4,5)) {
        path <- paste0("sample_", i, ".csv")
        fs <- c(fs, path)
        write(i*2, path)
      }
      zip(zipfile=fname, files=fs)
    }
  )
})

And the simple ui.R:

shinyUI(fluidPage(
  titlePanel(""),
  sidebarLayout(
    sidebarPanel(
      downloadButton("downloadData", label = "Download")
    ),
    mainPanel(h6("Sample download", align = "center"))
  )
))

I'm having nice output, except the error:

> shiny::runApp('C:/Users/user/AppData/Local/Temp/test')

Listening on http://127.0.0.1:7280
  adding: sample_1.csv (stored 0%)
  adding: sample_2.csv (stored 0%)
  adding: sample_3.csv (stored 0%)
  adding: sample_4.csv (stored 0%)
  adding: sample_5.csv (stored 0%)
Error opening file: 2
Error reading: 6

And no save dialog to save the archive. But in the temp folder the right archive is presented. How to properly share the archive?

Best Solution

You are using <- inside the downloadHandler function and should be using =. Also you may need to define the contentType:

library(shiny)

runApp(
  list(server = function(input, output) {  
    output$downloadData <- downloadHandler(
      filename = function() {
        paste("output", "zip", sep=".")
      },
      content = function(fname) {
        fs <- c()
        tmpdir <- tempdir()
        setwd(tempdir())
        for (i in c(1,2,3,4,5)) {
          path <- paste0("sample_", i, ".csv")
          fs <- c(fs, path)
          write(i*2, path)
        }
        zip(zipfile=fname, files=fs)
      },
      contentType = "application/zip"
    )
  }
  , ui = fluidPage(
    titlePanel(""),
    sidebarLayout(
      sidebarPanel(
        downloadButton("downloadData", label = "Download")
      ),
      mainPanel(h6("Sample download", align = "center"))
    )
  ))
)
Related Question