node将geojson转shp返回给前端的实现方法
node将geojson转shp需要调用[ogr2ogr][1]库来实现,在调用ogr2ogr库时,因为其通过调用gdal的工具来实现将
geojson转shp,所以需要安装gdal并配置环境变量。
参考文章:https://stackoverflow.com/questions/41253450/error-the-specified-module-could-not-be-found
第一:你要确定你的.node是好的,然后你可以继续下一步了
第二:你的.node发现不了可能是因为缺少了依赖关系,简单点说,就是缺少了.dll
第三:下载DependencyWalker,这个软件可以帮你确定一下缺少什么.dll,下载地址:http://www.dependencywalker.com/
第四:下载完DependencyWalker直接打开.node文件,将提示缺少的重要.dll放在.node同一级的目录下,当然你也可以不用下软件,直接把重要的.dll放在.node目录下就可以了。
第五:运行,就不会报错了。
环境配置完,可以进行代码实现了。
首先引入ogr2ogr库
constogr2ogr=require('ogr2ogr')
生成shp文件压缩包
//声明一个geojson变量也可以是geojson文件目录
vargeojson={
type:'FeatureCollection',
features:[
{
type:'Feature',
geometry
}
]
}
//shp保存目录
constzipPath='./export/shpfile.zip'
//创建文件写入流
varfile=fs.createWriteStream(zipPath)
//调用ogr2ogr进行转化
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)通过流的方式进行传递
varresPath=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
})
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=blobUrl
a.click()
URL.revokeObjectURL(blobUrl)
})
这里需要注意的地方是前端发送请求时需要设置一个参数responseType:'blob',这里用到了Blob对象,这里是从服务器接收到的文件流创建blob对象并使用该blob创建一个指向类型数组的URL,将该url作为a标签的链接目标,然后去触发a标签的点击事件从而文件下载。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。