如何将字节数组另存为角度的 ZIP



我正在尝试下载(使用FileSaver.saveAs)一个从服务器(nodejs\express)获取的字节数组作为zip。我设法将其下载为zip,但它无法打开(无效)。 我对数据的定义方式几乎没有什么错误 - 内容类型,服务器和客户端中的响应类型,我是否应该将其转换为 blob 等) - 但我想我用下面的详细代码克服了它们。 问题出在最后一个函数上,在exportAsZip函数中 - 数据以正确的大小到达那里,但将其转换为 Blob 会使它膨胀并可能损坏它。 这是我的代码(服务器端 - node.js-express使用中间件功能):这已经更新为固定代码:路由器是快速路由器:

router.use(<some route>,(req, res, next) => {
return getData(req.query).then((dataResult) => 
{
{
res.contentType('application/zip');
return res.send([dataResult]); //Data result is byte array
}).catch((err) => { 
console.error(err);
});
});

在客户端(角度): 这是组件函数:

downloadAsZip()
{
let fileName : string = <fileName>;
this.srv.getData().subscribe(result => 
{  
// const blob = new Blob([result], { type: 'application/octet-stream' }) 
/*This is the needed fix:*/
const byteArray = new Uint8Array(result);
const blob = new Blob([byteArray]);

this.fileService.exportAsZip(blob, fileName);
},
error => console.log(error) 
);

}

这是 srv.getData 代码:

getData() : Observable<any>
{
return this.http.get(<path>, /*{ responseType: 'blob' } - not needed*/) 
}

这是 fileService 函数 (exportAsZip):

exportAsZip(data, fileName)
{
/*The data is with a correct size, but converting it to a blob object inflate its size*/
/*this should be removed also*/
//const blobData: Blob = new Blob([data], {type: 'application/zip'});
FileSaver.saveAs(/*blobD*/data, fileName + '.zip');
}

修复了问题 - 主要更改是将字节数组数据转换为Uint8Array,然后创建一个将使用FileSaver.saveAs保存的blob。 此外,从获取请求标头中删除了 { responseType: 'blob' }。 上面的代码现已修复!

最新更新