node将geojson转shp返回给前端

3次阅读

共计 1432 个字符,预计需要花费 4 分钟才能阅读完成。

node 将 geojson 转 shp 需要调用 [ogr2ogr][1] 库来实现,在调用 ogr2ogr 库时,因为其通过调用 gdal 的工具来实现将

geojson 转 shp,所以需要安装 gdal 并配置环境变量,详情可参考此链接。环境配置完,可以进行代码实现了。

首先引入 ogr2ogr 库
    const ogr2ogr = require('ogr2ogr')
生成 shp 文件压缩包
    // 声明一个 geojson 变量也可以是 geojson 文件目录
    var geojson = {
      type: 'FeatureCollection',
      features: [
        {
          type: 'Feature',
          geometry
        }
      ]
    }
    // shp 保存目录
    const zipPath = './export/shpfile.zip'
    // 创建文件写入流
    var file = fs.createWriteStream(zipPath)
    // 调用 ogr2ogr 进行转化
    var ogr = ogr2ogr(geojson).project('EPSG:4326')
      .format('ESRI Shapefile')
      .skipfailures()
      .stream()
    ogr.pipe(file)
    
然后将 shp 压缩文件传给前端, 这里可以通过不同的方法进行传递

(1)通过 sendFile 直接进行传递

    var resPath = path.join(__dirname, '..', zipPath)
    res.sendFile(resPath)

(2)通过流的方式进行传递

    var resPath = path.join(__dirname, '..', zipPath)
    // 文件写入完成触发事件
    file.on('finish', function() {
      res.set({
        'Content-Type': 'application/zip',
        'Content-Disposition':
          'attachment; filename=' + encodeURI(name) + '.zip',
        'Content-Length': fs.statSync(zipPath).size
      })
      let fReadStream = fs.createReadStream(zipPath)
      fReadStream.pipe(res)
      fReadStream.on('end', function() {fs.unlinkSync(resPath)
      })
      fReadStream.on('error', function(err) {console.log(err)
      })
    })
最后是前端发送请求接收的代码
      axios.post('http://localhost:3000/jsontoshp', {responseType: 'blob'}).then(res => {const blobUrl = URL.createObjectURL(res.data)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.download = '文件名称'
        a.href = blobUrl
        a.click()
        URL.revokeObjectURL(blobUrl)
      })

这里需要注意的地方是前端发送请求时需要设置一个参数 responseType: ‘blob’,这里用到了 Blob 对象,这里是从服务器接收到的文件流创建 blob 对象并使用该 blob 创建一个指向类型数组的 URL,将该 url 作为 a 标签的链接目标,然后去触发 a 标签的点击事件从而文件下载。

正文完
 0