我的应用程序使用JSZip将用户提交的文件压缩为zip文件。然后,我想使用Leaflet.shapefile插件在我的应用程序上显示zip文件。
但是,构造函数仅接受ArrayBuffer。我查看了JSZip的文档,虽然支持ArrayBuffers,但找不到将JSZip对象转换为ArrayBuffer的任何显式方法。
function CreateZipFile(Files)
{
Response.type = "ArrayBuffer";
let zip = new JSZip();
for (let i = 0; i < Object.keys(Files).length; i++)
{
if (!CheckShapeExtensions(Files[i].name))
{
continue;
}
zip.file(Files[i].name, Files[i]);
}
zip.generateAsync({
type: 'blob',
compression: "DEFLATE",
compressionOptions: {
level: 9
},
name: zipfileName + ".zip"
});
return zip;
}
因为返回的zip不是数组缓冲区,所以接受zip文件的操作将引发以下错误。
leaflet.shpfile.js:13 Uncaught TypeError: Cannot read property 'isArrayBuffer' of undefined
at NewClass.initialize (leaflet.shpfile.js:13)
at new NewClass (Class.js:22)
at Object.L.shapefile (leaflet.shpfile.js:62)
at filescan (Account_2.js:115)
at HTMLInputElement.onchange (Account:156)
我应该如何将JSZip文件转换为ArrayBuffer?如果没有,我应该将zip文件写为数组缓冲区而不是JSZip对象吗?
最佳答案
function CheckShapeExtensions(file) {
return true
}
function CreateZipFile (files) {
const zip = new JSZip()
Array.from(files)
.filter(CheckShapeExtensions)
.forEach(file => {
zip.file(file.name, file)
})
// generateAsync returns a promise,
// means it is async
return zip.generateAsync({
type: 'arrayBuffer', // changed from blob to arrayBuffer
compression: 'DEFLATE',
compressionOptions: {
level: 9
}
})
}
// Simulate files you would get from a file input
// const files = input.files
const files = { 0: new File(['abc'], 'abc.txt'), length: 1 }
CreateZipFile(files).then(arrayBuffer => {
console.log(arrayBuffer.toString())
})
<script src="https://stuk.github.io/jszip/dist/jszip.min.js"></script>
关于javascript - 将JSZip对象转换为ArrayBuffer的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57804292/