Sending Zip file from server to client browser with Express and Archiver

2.4k Views Asked by At

I am a beginner with Node and I am trying to figure out how to create a zip file at the server then send it to the client and then download the zip file to the user's browser. I am using the Express framework and I am using Archiver to actually do the zipping. My server code is the following which was taken from Dynamically create and stream zip to client

router.get('/image-dl', function (req,res){

    res.writeHead(200, {
        'Content-Type': 'application/zip',
        'Content-disposition': 'attachment; filename=myFile.zip'
    });

    var zip = archiver('zip');

    // Send the file to the page output.
    zip.pipe(res);

    // Create zip with some files. Two dynamic, one static. Put #2 in a sub folder.
    zip.append('Some text to go in file 1.', { name: '1.txt' })
        .append('Some text to go in file 2. I go in a folder!', { name: 'somefolder/2.txt' })
        .finalize();
});

So its zipping two text files and returning the result. On the client side I am using the following function in a service to actually call that endpoint

downloadZip(){

    const headers = new Headers({'Content-Type': 'application/json'});

    const token = localStorage.getItem('token')
        ? '?token=' + localStorage.getItem('token')
        : '';

    return this.http.get(this.endPoint + '/job/image-dl' + token, {headers: headers})
        .map((response: Response) => {
            const result = response;
            return result;
        })
        .catch((error: Response) => {
            this.errorService.handleError(error.json());
            return Observable.throw(error.json());
        });

}

and then I have another function which calls downloadZip() and actually downloads the zip file to the user's local browser.

testfunc(){
    this.jobService.downloadZip().subscribe(
        (blah:any)=>{    
            var blob = new Blob([blah], {type: "application/zip"});
            FileSaver.saveAs(blob, "helloworld.zip");
        }
    );
}

When testfunc() is called, a zip file is downloaded to the user's browser however when I try to unzip it it creates a zip.cpgz file which then turns back into a zip file when clicked in an infinite loop which indicates that some kind of corruption happened. Can anyone see where I went wrong here?

0

There are 0 best solutions below