writeOGR not working on deployed app but woks on my machine


#1

Hi all
I have an app where the user can download a selected shapefile. I use an action button and the user enters the path to download to using a textInput (I couldn’t figure out how to get downloadhandler to work for shapefiles).
Anyway, it works nicely when running from my desktop, yet when deployed, nothing happens expect the app disconnects. The log has nothing to indicate a problem…
Code below.
Many thanks.
Andrew

  observeEvent(input$downloadShp,{
    shp.name<-input$select.shp  #Get the shapefile name
    shp.path<-input$shpfilepath #Get the path from the textInput
    idx<-name.lu$ShpAbbr[match(shp.name,name.lu$ShpName)] #Match the shapefile name ti the correct shapefile
    shp.nm<-get(paste0("locs.buff.proj.",idx)) #Get the correct shapefile
    tmp<-spTransform(shp.nm,CRS(proj4string)) #Transform it to NZTM
    file.name<-paste(shp.name,"_Coverage",sep="") #Append 'the'Coverage' to the shapefile name
    #Convert it into a SpatialPolygons DF
    IDs<-sapply(slot(tmp, "polygons"), function(x) slot(x, "ID"))
    df <- data.frame(rep(0, length(IDs)), row.names=IDs)
    tmp.exp<-SpatialPolygonsDataFrame(tmp,data=as.data.frame(df))#, proj4string=CRS(proj4string))
    
    #Make sure the last character is not an "/". If so, remove it 
    if(substr(shp.path,nchar(shp.path),nchar(shp.path))=="/"){
      shp.path<-substr(shp.path,1,(nchar(shp.path)-1))
    }
    #Create the file path
    dir.create(file.path(shp.path), showWarnings = FALSE)
    shp.path<-paste0(shp.path,"/",file.name,".shp") #Somewhere said this line might be necessary...
    writeOGR(obj=tmp.exp, dsn=shp.path, layer=file.name, driver="ESRI Shapefile", overwrite_layer=TRUE)
  })

#2

Didn’t solve my problem above, but did manage to get downloadHandler working, so now not necessary. :slight_smile:


#3

fwiw you definitely shouldn’t have .shp at the end - you could end up with “file.shp.shp” (though possibly that is OS and version dependent. Also, GDAL is investigating “auto-detection” of desired format in future releases.)

It’s counter-intuitive but the dsn/layer distinction is GDAL’s way of treating all formats like a database, with “layers” - a shapefile in a folder is one layer, and that folder can be treated like a container of layers. (Some single-file formats can contain multiple layers). A more intutive wrapper around writeOGR for shapefile is

raster::shapefile(obj, "/path/to/file.shp")

#4

Thanks for that reply. Will definitely be helpful in a number of other places where I am writing shapefiles to a directory. Yeah, I thought the .shp at the end of dsn was weird, but it seemed to work. But I’ve never used it in other places so will remove it here.
Thanks again