how to save byte array as zip in angular

丶灬走出姿态 提交于 2021-01-29 14:00:56

问题


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

}

This is the srv.getData code:

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

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

回答1:


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 !



来源:https://stackoverflow.com/questions/56723781/how-to-save-byte-array-as-zip-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!