闪亮:下载zip档案

时间:2014-11-12 07:21:47

标签: r shiny

我无法使闪亮的downloadHandler输出zip文件:

# 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)
    }
  )
})

简单的ui.R

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

除了错误之外,我的输出效果很好:

> 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

没有用于保存存档的保存对话框。但是在temp文件夹中显示了正确的存档。如何正确分享档案?

2 个答案:

答案 0 :(得分:11)

您在downloadHandler函数中使用了<-,并且应该使用=。您还可能需要定义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"))
    )
  ))
)

答案 1 :(得分:0)

您还可以使用tar压缩文件夹:

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

    content <- function(file) {
      tar(file, "file/path/")
    }
  )