typescript 使用 Angular 下载 zip 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44112470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:34:24  来源:igfitidea点击:

Download zip file using Angular

restangulartypescript

提问by edkeveked

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.

现在已经几个小时了,因为我想弄清楚如何使用 Angular 下载 zip 文件。下载的文件比原始文件小。我点击了这个链接How do I download a file with Angular2

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

我不只是<a>出于身份验证原因使用标签进行下载。

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

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

  }

回答by Manuel Vergara

  1. In responseType you need to assign a string, in this case, is arraybuffer(Angular 5+)
  1. 在 responseType 中,您需要分配一个字符串,在这种情况下,是arraybufferAngular 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:
  1. 我们可以做一个窗口,使用下一个代码直接下载我们的文件:

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

回答by SSD

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

您需要多个插件才能使用 angular 下载 zip 文件:

  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 JSZipand JSZipUtils
  1. angular-file-saver.bundle

    这个插件将捆绑 Blob.js 和 FileSaver.js 遵循所有说明,现在只需在您的控制器和模块上添加依赖项。

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

  2. 添加JSZipJSZipUtils

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

包含文件: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);
});

回答by Minakshee Yuvraj Kolte

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

在 Angular 中不需要 jsZip-util ,您可以简单地使用标头选项进行服务调用。

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

      }