当前位置: 首页 > 后端技术 > Node.js

node返回geojson转shp给前端

时间:2023-04-03 11:18:29 Node.js

node调用ogr2??ogr库将geojson转shp。调用ogr2??ogr库时,由于使用gdal工具将geojson转shp,需要安装gdal并配置环境变量,详见此链接。环境配置好后,就可以实现代码了。先引入ogr2ogr库constogr2ogr=require('ogr2ogr')生成shp文件压缩包//声明一个geojson变量或者一个geojson文件目录vargeojson={type:'FeatureCollection',features:[{type:'Feature',geometry}]}//shp存储目录constzipPath='./export/shpfile.zip'//创建文件写入流varfile=fs.createWriteStream(zipPath)//调用ogr2??ogr进行转换varogr=ogr2ogr(geojson).project('EPSG:4326').format('ESRIShapefile').skipfailures().stream()ogr.pipe(file)然后将shp压缩文件传给前端,可以通过不同的方式传递(1)通过sendFile直接传输varresPath=path.join(__dirname,'..',zipPath)res.sendFile(resPath)(2)通过stream传输varresPath=path.join(__dirname,'..',zipPath)//文件写入完成触发事件file.on('finish',function(){res.set({'Content-Type':'application/zip','Content-Disposition':'attachment;filename='+encodeURI(名称)+'.zip','Content-Length':fs.statSync(zipPath).size})letfReadStream=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=>{constblobUrl=URL.createObjectURL(res.data)consta=document.createElement('a')a.style.display='none'a.download='文件名'a.href=blobUrla.click()URL.revokeObjectURL(blobUrl)})这里需要注意的是,前端发送请求的时候需要设置一个参数responseType:'blob',这里使用的是Blob对象,这里是创建一个从服务器接收到的文件流中提取blob对象,并用这个blob创建一个指向类型数组的URL,将URL作为a标签的链接目标,然后触发a标签的点击事件进行下载文件