Angular 2文件下载

时间:2018-01-12 11:16:39

标签: angular download

我试图从休息服务下载文件(可以是任何格式),我可以检索文件并保存它,但格式始终是XML文件,也是我没有在Windows中打开的文件。

ngOnInit() {
    this.downloading();
}

downloading() {
    this.route.params
    .switchMap((params: Params) =>
        this.service.downloadFile(params["ao_id"], params["id"])
    )
    .subscribe(blob => {

        importedSaveAs(blob, this.fileName);

        var fileURL = URL.createObjectURL(blob);
        window.open(fileURL);
    });
}

downloadfile() {
    this.route.params
    .switchMap((params: Params) =>
        this.service.getMyFileFromBackend(params["ao_id"], params["id"])
    )
    .subscribe(
        res => this.extractData(res),
        (error: any) => Observable.throw(error || "Server error")
    );
}

在myservice中

downloadFile(ao_id: string, id: string): Observable<Blob> {
    const cpHeaders = new Headers({
        "Content-Type": "application/x-www-form-urlencoded"
    });
    let cpParams: URLSearchParams = new URLSearchParams();
    cpParams.set("ao_id", ao_id);
    cpParams.set("type", id);

    const options = new RequestOptions({
        headers: cpHeaders,
        search: cpParams,
        responseType: ResponseContentType.Blob
    });
    return this.http
    .get(this.downloadUrl, options)
    .map(res => res.blob())
    .catch(this.handleError);
}

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码下载任何文件。

public downloadFile(ao_id: string, id: string) {    
            let downloadUrl= '<url with query param>';
            return Observable.create(observer => {
                let xhr = new XMLHttpRequest();

                xhr.open('GET', downloadUrl, true);
                xhr.setRequestHeader('Content-type', 'application/json');
                xhr.responseType='blob';

                xhr.onreadystatechange = function () {
                  if (xhr.readyState === 4) {
                    if (xhr.status === 200) { 
                        debugger;
                      var contentType = 'application/octet-stream';
                      var blob = new Blob([xhr.response], { type: contentType 
                    });
                      observer.next(blob);
                      observer.complete();
                      return observer;

                    } else {
                      observer.error(xhr.response);
                    }
                  }
                }
                debugger;
                xhr.send();
              });
        }