1

I have a method that imports shapefile to PostgreSQL (using GeoTools), it takes as arguments the path of the shapefile (it's working fine). The problem is I want the user to select a shapefile from his local machine, and I can't find a way to save the value of the selected shapefile's path, since getelementbyId.value of an input file returns 'C:/fakepath'.

Import shapefile to PostgreSQL/PostGIS method :

  public ShapeToPostGIS (String a,String b) throws  NoSuchAuthorityCodeException, FactoryException, MalformedURLException, IOException, ClassNotFoundException, SQLException {
    String shapeFileLoc =a; //location of the shapefile
    String postGISTblName = b;//name to give to the newly created table 
    String shapeEPSG = "EPSG:4326";//the epsg to use if not found from shpefile
        try {

            // shapefile loader
            Map shapeParams = new HashMap();
            shapeParams.put("url", new File(shapeFileLoc).toURL());
            shapeParams.put( "charset", "ISO-8859-7" );//for greek chars
            DataStore shapeDataStore = DataStoreFinder.getDataStore(shapeParams);       

            // feature type
            String typeName = shapeDataStore.getTypeNames()[0];
            FeatureSource<SimpleFeatureType,SimpleFeature> featSource = shapeDataStore.getFeatureSource(typeName);
            FeatureCollection<SimpleFeatureType,SimpleFeature> featSrcCollection = featSource.getFeatures();
            SimpleFeatureType ft = shapeDataStore.getSchema(typeName);

            // feature type copy to set the new name
            SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
            builder.setName(postGISTblName);
            builder.setAttributes(ft.getAttributeDescriptors());
            builder.setCRS(ft.getCoordinateReferenceSystem());

            SimpleFeatureType newSchema = builder.buildFeatureType();

            // management of the projection system
            CoordinateReferenceSystem crs = ft.getCoordinateReferenceSystem();

            // test of the CRS based on the .prj file
            Integer crsCode = CRS.lookupEpsgCode(crs, true);

            Set<ReferenceIdentifier> refIds = ft.getCoordinateReferenceSystem().getIdentifiers();
            if ( ( (refIds == null) || (refIds.isEmpty() ) ) && (crsCode == null) ) {
                CoordinateReferenceSystem crsEpsg = CRS.decode(shapeEPSG);
                newSchema = SimpleFeatureTypeBuilder.retype(newSchema,crsEpsg);
            }

            Map postGISParams = new HashMap<String,Object>();
            postGISParams.put("dbtype", "postgis");         //must be postgis
            postGISParams.put("host", "localhost");         //the name or ip address of the machine running PostGIS
            postGISParams.put("port",5433);                 //the port that PostGIS is running on (generally 5432)
            postGISParams.put("database", "DB");       //the name of the database to connect to.
            postGISParams.put("user", "postgres");          //the user to connect with
            postGISParams.put("passwd", "goblin");    //the password of the user.
            postGISParams.put("schema", "public");        //the schema of the database
            postGISParams.put("create spatial index", Boolean.TRUE);
            DataStore dataStore = null;
            try {
            // storage in PostGIS
            dataStore = DataStoreFinder.getDataStore(postGISParams);
            } catch (Exception e){
            System.out.println("problem with datastore:"+e);
            }
           
            if (dataStore == null) {
             System.out.println("ERROR:dataStore is null");
            } 
            
            dataStore.createSchema(newSchema);
            @SuppressWarnings("unchecked")
            FeatureStore<SimpleFeatureType,SimpleFeature> featStore = (FeatureStore<SimpleFeatureType,SimpleFeature>)dataStore.getFeatureSource(postGISTblName);
        
            featStore.addFeatures(featSrcCollection);
           
        } catch (IOException e) {
            System.out.println("ERROR:"+e);
        }

       System.out.println("Shapefile imported successfully !!!!!");

}

I tried this approach, but it is surely false :

  <form action='#' onsubmit="load()">
          <input type='file' id='path'>
          <input type='text' id='name'>
          <input type='submit' value='Load'>
      </form> 
      <script>
  async function load() {
 
  var path=getElementById('path').value;
  var shpfileName=getElementById('name').value;
 
  const encodpath= encodeURIComponent(path);
  const encodname= encodeURIComponent(shpfileName);

 const response = await fetch("http://localhost:8083/shape?path="+encodpath+"&name="+encodname)
 var data = await response.json();
  console.log(data);

};
      </script>

in my SpringBoot controller :

 @GetMapping("/shape")
     public void ImportshapefiletoDB(@RequestParam("path") String path,@RequestParam("name") String name) throws NoSuchAuthorityCodeException, MalformedURLException, ClassNotFoundException, FactoryException, IOException, SQLException {
        
        ShapeToPostGIS SHPTOPOSTGIS = new ShapeToPostGIS(path,name);
         
         //in the database, the geometry column is named ' the_geom ' !! replacing it with 'geom'
         regservice.alterMyTableRenameMyColumn(name,"the_geom","geom");
         
 }

Is there any approach I can try? I've searched everywhere but couldn't find a way to import a shapefile selected by a user from his local machine.

6
  • Have you looked at the GeoServer code that does this?
    – Ian Turton
    May 22 at 11:32
  • There's scores of ways to do this, but all of them involve either sending a zip of the shapefile to the server or writing client-side code to extract the needed data into a a web-friendly format and POSTing that back to the server for further processing.
    – Vince
    May 22 at 11:38
  • @IanTurton Ive worked with the Geoserver Code but only to publish the layer that I ALREADY have in my database.
    – Fatima22
    May 22 at 12:04
  • @Vince I checked some tutoriels that shows how to work with the zip of the shapefile, but I couldn't find how to sent that to the server. neither working with the extracted data from client-side code ... i will appreciate any little help
    – Fatima22
    May 22 at 12:10
  • 1
    How to send a zip file to a web server is a generic IT task better researched in Stack Overflow
    – Vince
    May 22 at 14:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.