我有一个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);
}

当前回答

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

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

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

其他回答

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

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

在你的组件中。

我分享了帮助我的解决方案(任何改进都非常感谢)

关于你的服务“pservice”:

getMyFileFromBackend(typeName: string): Observable<any>{
    let param = new URLSearchParams();
    param.set('type', typeName);
    // setting 'responseType: 2' tells angular that you are loading an arraybuffer
    return this.http.get(http://MYSITE/API/FILEIMPORT, {search: params, responseType: 2})
            .map(res => res.text())
            .catch((error:any) => Observable.throw(error || 'Server error'));
}

组成部分:

downloadfile(type: string){
   this.pservice.getMyFileFromBackend(typename).subscribe(
                    res => this.extractData(res),
                    (error:any) => Observable.throw(error || 'Server error')
                );
}

extractData(res: string){
    // transforme response to blob
    let myBlob: Blob = new Blob([res], {type: 'application/vnd.oasis.opendocument.spreadsheet'}); // replace the type by whatever type is your response

    var fileURL = URL.createObjectURL(myBlob);
    // Cross your fingers at this point and pray whatever you're used to pray
    window.open(fileURL);
}

在组件部分,无需订阅响应即可调用服务。订阅 有关openOffice mime类型的完整列表,请参见:http://www.openoffice.org/framework/documentation/mimetypes/mimetypes.html

通过ajax下载文件总是一个痛苦的过程,在我看来,最好让服务器和浏览器来完成内容类型协商的工作。

我认为最好有

<a href="api/sample/download"></a> 

去做它。这甚至不需要打开任何新窗口之类的东西。

示例中的MVC控制器可以如下所示:

[HttpGet("[action]")]
public async Task<FileContentResult> DownloadFile()
{
    // ...
    return File(dataStream.ToArray(), "text/plain", "myblob.txt");
}

创建一个临时锚标记,然后用Javascript以编程方式单击它

async function downloadFile(fileName) { const url = document.getElementById("url").value const link = document.createElement('a'); link.href = await toDataURL(url); link.setAttribute('download', fileName ? fileName : url.split('/').pop()); link.setAttribute('target', 'blank'); document.body.appendChild(link); link.click(); } function toDataURL(url) { return fetch(url) .then((response) => { return response.blob(); }) .then((blob) => { return URL.createObjectURL(blob); }); } <input id="url" value="https://images.pexels.com/photos/1741205/pexels-photo-1741205.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"/> <button onclick="downloadFile('test')">Download</button>

这是为那些寻找如何使用HttpClient和文件保存器的人准备的:

点击安装

NPM安装文件保护程序 NPM install @types/file-saver

API服务类:

export() {
    return this.http.get(this.download_endpoint, 
        {responseType: 'blob'});
}

组件:

import { saveAs } from 'file-saver';
exportPdf() {
    this.api_service.export().subscribe(data => saveAs(data, `pdf report.pdf`));
}