R闪亮下载压缩的shp文件

问题描述 投票:0回答:1

我尝试开发一个闪亮的应用程序,其中创建了一个 sf 对象,并且可以作为 zip 文件夹中的 shp 文件下载。最好将 shp 几何图形打包在子文件夹中:

-myzip |-我的几何 |--myshape.shp

我尝试修改(tar 和 zip)以下代码,但从未成功。

library(shiny)
library(sf)

##sf object
data <- data.frame(
  x = c(1, 2, 3),
  y = c(4, 5, 6)
)
colnames(data) <- c("x", "y")

# Converting to sf object
sf_object <- st_as_sf(data, coords = c("x", "y"))


ui <- fluidPage(
  titlePanel("Download zip"),
  
  mainPanel(
                   downloadButton("downloadData", label = "Download")
      
  )
)

server<-function(input,output,session){
  output$downloadData <- downloadHandler(
    filename = function() {
      paste("myzip", "zip", sep = ".")
    },
    content = function(fname) {
      fs <- c()
      tmpdir <- tempdir()
      setwd(tempdir())
      path <- paste0(tmpdir,"/mysf_object",".shp")
      fs <- c(sf_object, path)
      st_write(sf_object,path)
      zipr(zipfile = fname, files = fs)
    },
    contentType = "application/zip"
  )
  
}

# Run the application
shinyApp(ui = ui, server = server)
shiny download zip
1个回答
0
投票

试试这个。您的版本的问题之一是您没有创建目录,并且

st_write
创建了四个文件,但您只在对
zip::zipr

的调用中包含其中一个文件
 output$downloadData <- downloadHandler(
    filename = function() {
      "myzip.zip"
    },
    content = function(fname) {
      tmpdir <- tempdir()
      setwd(tempdir())
      directory <- file.path(tmpdir, "mygeometry")
      dir.create(directory)
      path <- file.path(directory, "mysf_object.shp")
      st_write(sf_object, path)

      files <- file.path("mygeometry", list.files("mygeometry/"))
      
      zip::zipr(zipfile = fname,
           files = files,
           include_directories = TRUE,
           mode = "mirror")
    }
  )
© www.soinside.com 2019 - 2024. All rights reserved.