我正在使用 vue3 加载 shp 文件。
使用的 shp 库是 https://github.com/calvinmetcalf/shapefile-js。 shpjs 的版本是“^5.0.1”。
这是代码
<el-upload
ref="uploadRef"
action="/"
v-model:file-list="state.uploadList"
:on-change="uploadFile"
>
<template #trigger>
<el-button type="primary">select file</el-button>
</template>
</el-upload>
import shp from 'shpjs';
import { Feature, GeoJSON } from 'geojson';
const uploadFile = async (file) => {
const format = file.name.split('.').at(-1).toLowerCase();
let geojson: FeatureCollection<any>;
switch (format) {
case 'shp': {
console.log( await file.raw.arrayBuffer() );
const parsed = await shp(await file.raw.arrayBuffer());
geojson = parsed;
break;
}
}
}
等待 file.raw.arrayBuffer() 输出
ArrayBuffer(59664156)字节长度:59664156
但是从缓冲区解析 shp - shp(await file.raw.arrayBuffer()) 抛出错误
Uncaught (in promise) Error: Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html
at h.readEndOfCentral (shpjs.js?v=9c11b5bb:1045:63)
at h.load (shpjs.js?v=9c11b5bb:1065:40)
at shpjs.js?v=9c11b5bb:290:23
at async unzip_default (shpjs.js?v=9c11b5bb:6488:3)
at async parseZip (shpjs.js?v=9c11b5bb:6970:15)
at async Module.loadGeojson (shp.ts:61:24)
如果您上传的文件以 .shp 结尾,它不是 zip 文件,而是一个形状,因此您需要使用 parseShp 方法
import {parseShp} from 'shpjs'
或者它可以作为 shp.parseShp
提供并将数组缓冲区传递给该方法,即 await parseShp(await file.raw.arrayBuffer());