如何将字节数组另存为zip [英] how to save byte array as zip in angular

查看:48
本文介绍了如何将字节数组另存为zip的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试(使用FileSaver.saveAs)下载从服务器(nodejs \ express)获取的zip字节数组.我设法将其下载为zip,但无法打开(无效).关于数据的定义方式,我几乎没有遗漏任何内容-服务器和客户端中的内容类型,responseType,是否应该将其转换为blob等)-但我认为我在详细内容中克服了它们下面的代码.问题出在最后一个功能中,即 exportAsZip 函数中-数据以正确的大小到达该位置,但是将其转换为Blob会对其进行充气,并可能损坏它.这是我的代码(服务器端-使用中间件功能的node.js-express):此信息已按照固定代码进行更新:路由器是快速路由器:

I'm trying to download (using FileSaver.saveAs) a byte array getting from the server (nodejs\express) as a zip. I'm manage to download it as zip, but it doesn't open (it is invalid). I had few miss-clarities regarding the way the data should be defined - content type, responseType both in the server and in the client, should I convert it to a blob, etc) - but I think I over-come them with the detailed below code. The problem is at the final function, in the exportAsZip function - the data reaches there in the right size, but converting it to a Blob inflate it and probably corrupt it. Here is my code (server side - node.js-express using middleware function): THIS IS ALREADY UPDATED AS FIXED CODE: The router is express-router:

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);
    });
});

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

In the client side (angular): This is the component function:

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代码:

This is the srv.getData code:

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

这是fileService函数(exportAsZip):

This is the fileService function (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');
}

推荐答案

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

Fixed the problem - The main change is to convert the byte Array data to Uint8Array and then create a blob which will be saved using the FileSaver.saveAs. Also, removed the { responseType: 'blob' } from the get request header. The above code is now fixed !

这篇关于如何将字节数组另存为zip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆