我有一个WebApi / MVC应用程序,我正在为它开发一个angular2客户端(以取代MVC)。我在理解Angular如何保存文件时遇到了一些麻烦。

请求是可以的(与MVC一起工作很好,我们可以记录接收到的数据),但我不知道如何保存下载的数据(我主要遵循与本文相同的逻辑)。我确信这是愚蠢的简单,但到目前为止,我根本没有领会它。

组件函数的代码如下。我尝试了不同的替代方案,blob方式应该是我所理解的方式,但URL中没有createObjectURL函数。我甚至不能在窗口中找到URL的定义,但显然它存在。如果我使用FileSaver.js模块,我得到同样的错误。所以我猜这是最近改变的或者还没有实现的东西。我如何触发文件保存在A2?

downloadfile(type: string){

    let thefile = {};
    this.pservice.downloadfile(this.rundata.name, type)
        .subscribe(data => thefile = new Blob([data], { type: "application/octet-stream" }), //console.log(data),
                    error => console.log("Error downloading the file."),
                    () => console.log('Completed file download.'));

    let url = window.URL.createObjectURL(thefile);
    window.open(url);
}

为了完整起见,获取数据的服务如下所示,但它所做的唯一一件事是发出请求并在没有映射的情况下传递数据:

downloadfile(runname: string, type: string){
   return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type)
            .catch(this.logAndPassOn);
}

当前回答

如果你只发送参数到一个URL,你可以这样做:

downloadfile(runname: string, type: string): string {
   return window.location.href = `${this.files_api + this.title +"/"+ runname + "/?file="+ type}`;
}

在接收参数的服务中

其他回答

如果你不需要在请求中添加头文件,在Angular2中下载一个文件,你可以做一个简单的(KISS原则):

window.location.href='http://example.com/myuri/report?param=x';

在你的组件中。

试试这个!

1 -安装显示保存/打开文件弹出的依赖项

npm install file-saver --save
npm install -D @types/file-saver

2-用这个功能创建一个服务来接收数据

downloadFile(id): Observable<Blob> {
    let options = new RequestOptions({responseType: ResponseContentType.Blob });
    return this.http.get(this._baseUrl + '/' + id, options)
        .map(res => res.blob())
        .catch(this.handleError)
}

3-在组件中使用“file-saver”解析blob

import {saveAs as importedSaveAs} from "file-saver";

  this.myService.downloadFile(this.id).subscribe(blob => {
            importedSaveAs(blob, this.fileName);
        }
    )

这对我很管用!

<a href=“my_url” 下载=“我的文件名”>下载文件</a>

My_url应该具有相同的原点,否则它将重定向到该位置

我找到了一个从angular 2下载而不会损坏的解决方案, 使用spring MVC和angular 2

我的返回类型是:- responseentity从java结束。这里我发送字节[]数组从控制器返回类型。

第二步-在你的工作空间中包含文件保存器-在索引页中:

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>

第3 - at组件ts编写以下代码:

import {ResponseContentType} from '@angular.core';

let headers = new Headers({ 'Content-Type': 'application/json', 'MyApp-Application' : 'AppName', 'Accept': 'application/pdf' });
        let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob });
            this.http
            .post('/project/test/export',
                    somevalue,options)
              .subscribe(data => {

                  var mediaType = 'application/vnd.ms-excel';
                  let blob: Blob = data.blob();
                    window['saveAs'](blob, 'sample.xls');

                });

这将为您提供xls文件格式。如果需要其他格式,请使用正确的扩展名更改介质类型和文件名。

你也可以直接从你的模板下载一个文件,你使用下载属性和[attr。你可以从组件中提供一个属性值。 这个简单的解决方案应该适用于大多数浏览器。

<a download [attr.href]="yourDownloadLink"></a>

参考:https://www.w3schools.com/tags/att_a_download.asp