How to download multiple csv files in a zipped folder in Shiny

4,131 views
Skip to first unread message

Edward Lee

unread,
Jan 30, 2015, 12:05:21 AM1/30/15
to shiny-...@googlegroups.com
Hi - 

Using base package data, I put together a simple downloadHandler code that outputs multiple files into one zipped folder. I seem to get an error that I'm not sure how to correct. Could someone please help me point out where the gap in this code is?

Thanks,
Ed

library(shiny)

# server.R
server <- function(input, output) {

  datasetInput <- reactive({
    return(list(rock=rock, pressure=pressure, cars=cars))
  })

  output$downloadData <- downloadHandler(
    filename = 'pdfs.zip',
    content = function(fname) {
      tmpdir <- tempdir()
      setwd(tempdir())
      print(tempdir())

      fs <- c("rock.csv", "pressure.csv", "cars.csv")
      write.csv(datasetInput()$rock, file = "rock.csv", sep =",")
      write.csv(datasetInput()$pressure, file = "pressure.csv", sep =",")
      write.csv(datasetInput()$cars, file = "cars.csv", sep =",")
      print (fs)

      zip(zipfile=fname, files=fs)
    },
    contentType = "application/zip"
  )

}

# ui.R
ui <- shinyUI(fluidPage(
  titlePanel('Downloading Data'),
  sidebarLayout(
    sidebarPanel(
      downloadButton('downloadData', 'Download')
    ),
    mainPanel()
    )
  )
  )

shinyApp(ui = ui, server = server)

Joe Cheng

unread,
Jan 30, 2015, 1:15:57 AM1/30/15
to Edward Lee, shiny-...@googlegroups.com
I'd put a browser() call right after the call to zip(), and look in the temp directory. Possibly you'll find that instead of fname, zip decided to save it to fname + ".zip"? If so, you'll have to rename it to fname. Sorry about that.

--
You received this message because you are subscribed to the Google Groups "Shiny - Web Framework for R" group.
To unsubscribe from this group and stop receiving emails from it, send an email to shiny-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/shiny-discuss/CABaTaxWVirBhUxqu2UoF_JArUE_vMk%2Bx9MCce3wQpHawu36TwA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Edward Lee

unread,
Jan 30, 2015, 10:39:05 AM1/30/15
to Joe Cheng, shiny-...@googlegroups.com
Thank you! 

Just in case anyone else is looking for a solution, I tried "if(file.exists(paste0(fname, ".zip"))) {file.rename(paste0(fname, ".zip"), fname)}" after the zip() call, and it worked like how I wanted. 

Joe Cheng

unread,
Jan 30, 2015, 1:48:09 PM1/30/15
to Edward Lee, shiny-...@googlegroups.com
That's such a shame. I'll see if I can make this unnecessary (by giving you a value for fname that includes the correct extension)--your "if" there is a good idea, hopefully your code will not need to change.
Reply all
Reply to author
Forward
0 new messages