我有一个 Shiny 应用程序,可以读取 gpx 轨迹文件并对其进行缓冲。然后,我希望用户能够将该 shapefile 下载到他们选择的目的地。我一直在尝试使用该downloadHandler功能,但到目前为止我还没有感到高兴。
我创建的 shapefile 的名称为trk_buff. 在 RI 中可以只使用:
my_dsn<-"C:\\Documents\\TrackFiles"
writeOGR(obj=trk_buff, dsn=my_dsn, layer="BufferedTracks", driver="ESRI Shapefile")
Run Code Online (Sandbox Code Playgroud)
我尝试使用 downloadHandler :
output$downloadData<-downloadHandler(
filename=function(file){trk_buff},
content=function(file){
writeOGR(obj=trk_buff, dsn=file, layer="BufferedTracks", driver="ESRI Shapefile")
})
Run Code Online (Sandbox Code Playgroud)
但我显然做错了什么,因为什么也没发生......:|
编辑添加 如果我使用操作按钮和文本文件框的组合,我可以获得我想要的行为。但这有点笨拙,并且涉及用户显式写入文件路径而不是搜索它,这可能会导致错误:例如在 ui.RI 中有:
textInput("filepath","Filepath to download data"),
actionButton("act1","Download shapefile")
Run Code Online (Sandbox Code Playgroud)
在server.RI中有:
action_btn_code <- eventReactive(input$act1, {
file_path<-input$filepath
writeOGR(obj=trk_buff, dsn=paste(file_path,"/Tracks",sep=""), layer="BufferedTracks",
driver="ESRI Shapefile", overwrite_layer=TRUE)
})
Run Code Online (Sandbox Code Playgroud)
以下内容对我有用。这个想法是你必须压缩 shapefile,因为downloadHandler只能处理下载一个文件。
output$download_shp <- downloadHandler(
filename = "shapefile.zip",
content = function(file) {
data = trk_buff() # I assume this is a reactive object
# create a temp folder for shp files
temp_shp <- tempdir()
# write shp files
writeOGR(data, temp_shp, "trk_buff", "ESRI Shapefile",
overwrite_layer = TRUE)
# zip all the shp files
zip_file <- file.path(temp_shp, "trk_buff_shp.zip")
shp_files <- list.files(temp_shp,
"trk_buff",
full.names = TRUE)
# the following zip method works for me in linux but substitute with whatever method working in your OS
zip_command <- paste("zip -j",
zip_file,
paste(shp_files, collapse = " "))
system(zip_command)
# copy the zip file to the file argument
file.copy(zip_file, file)
# remove all the files created
file.remove(zip_file, shp_files)
}
)
Run Code Online (Sandbox Code Playgroud)