edkeveked
edkeveked

Reputation: 18381

Download zip file using Angular

It has been hours now, since I am trying to figure out how to download a zip file using Angular. The file downloaded is smaller than the original file. I followed this link How do I download a file with Angular2.

I am not simply using the <a> tag for the download for authentication reason.

service

 downloadfile(filePath: string){
        return this.http
            .get( URL_API_REST + 'downloadMaj?filePath='+ filePath)
            .map(res => new Blob([res], {type: 'application/zip'}))
    }

component

downloadfileComponent(filePath: string){
        this.appService.downloadfile(filePath)
            .subscribe(data => this.getZipFile(data)),
                error => console.log("Error downloading the file."),
                () => console.log('Completed file download.');
    }


getZipFile(data: any){
        var a: any = document.createElement("a");
        document.body.appendChild(a);

        a.style = "display: none";
        var blob = new Blob([data], { type: 'application/zip' });

        var url= window.URL.createObjectURL(blob);

        a.href = url;
        a.download = "test.zip";
        a.click();
        window.URL.revokeObjectURL(url);

    }

rest api

public void downloadMaj(@RequestParam(value = "filePath") String filePath, HttpServletResponse response) {

        System.out.println("downloadMaj");
        File fichierZip = new File(filePath);

        try {
            System.out.println("nom du fichier:" + fichierZip.getName());
            InputStream inputStream = new FileInputStream(fichierZip);

            response.addHeader("Content-Disposition", "attachment; filename="+fichierZip.getName());
            response.setHeader("Content-Type", "application/octet-stream");

            org.apache.commons.io.IOUtils.copy(inputStream, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Anyone could tell why all the file is not downloaded?

Solved

downloadfile(filePath: string) {
        return this.http
          .get( URL_API_REST + 'download?filePath=' + filePath, {responseType: ResponseContentType.ArrayBuffer})
          .map(res =>  res)
      }
private getZipFile(data: any) {
    const blob = new Blob([data['_body']], { type: 'application/zip' });

    const a: any = document.createElement('a');
    document.body.appendChild(a);

    a.style = 'display: none';    
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = test.zip;
    a.click();
    window.URL.revokeObjectURL(url);

  }

Upvotes: 13

Views: 62739

Answers (4)

Kalakar Sahoo
Kalakar Sahoo

Reputation: 31

I use FileSaver to save files on my local machine. It accepts either blob or string data and saves the file with the given/default name. From the official document:

function FileSaver.saveAs(data: string | Blob, filename?: string, options?: FileSaver.FileSaverOptions): void

Download.Service.ts

downloadFile() {
    return this.http.get(url, { params, responseType: 'arraybuffer', observe: 'response' }).pipe(
        map(res => res)
    );
}

my.component.ts

this.downloadService.downloadFile().subscribe((response: HttpResponse<any>) => {
    if(response.body) {
        let fileName = "download.zip";
        const cDisposition: string = response.headers.get('content-disposition');
        if (cDisposition && cDisposition.indexOf(';filename=') > -1) {
            fileName = cDisposition.split(';filename=')[1];
        }

        const data = new Blob([new Uint8Array(response.body)], {
            type: 'application/octet-stream'
        });
        FileSaver.saveAs(data, fileName);
    }
})

Upvotes: 0

In Angular there is no need of jsZip-util ,you can simple make an service call with header options.

public zipAndDownload(url): Observable<any> {
       const options:any = {
        headers: new HttpHeaders({'Content-Type': 'file type of an particular document'}),
        withCredentials: true,
        responseType:'arraybuffer'
      }; 
        return this.http.get<Content>(url,options);

      }

Upvotes: 1

Manuel Vergara
Manuel Vergara

Reputation: 266

  1. In responseType you need to assign a string, in this case, is arraybuffer (Angular 5+)

downloadFile(filename: string) {
  return this.http.get(URL_API_REST + 'download?filename=' + filename, {
    responseType: 'arraybuffer'
  });
}

  1. We can do a window to download directly our file using next code:

this.myService.downloadFile(filename).subscribe(data => {
  const blob = new Blob([data], {
    type: 'application/zip'
  });
  const url = window.URL.createObjectURL(blob);
  window.open(url);
});

Upvotes: 25

SSD
SSD

Reputation: 201

There are multiple plugins you'll need to get zip download working using angular:

  1. angular-file-saver.bundle

    This plugin will bundle Blob.js and FileSaver.js follow all instructions now just add dependencies on your controller and module.

    .module('fileSaverExample', ['ngFileSaver']) .controller('ExampleCtrl', ['FileSaver', 'Blob', ExampleCtrl]);

  2. add JSZip and JSZipUtils

Include files:jszip.js, jszip-utils.js, angular-file-saver.bundle.js

var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");

// when everything has been downloaded, we can trigger the dl
zip.generateAsync({type:"blob"}).then(function (blob) { // 1) generate the zip file
FileSaver.saveAs(blob, "downloadables.zip");                          // 2) trigger the download
}, function (err) {
    console.log('err: '+ err);
});

Upvotes: 2

Related Questions