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

当前回答

创建一个临时锚标记,然后用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>

其他回答

下载angular 2.4的*.zip解决方案。x:你必须从@angular/http导入ResponseContentType,并将responseType更改为ResponseContentType。ArrayBuffer(默认为ResponseContentType.Json)

getZip(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> {
 let headers = this.setHeaders({
      'Content-Type': 'application/zip',
      'Accept': 'application/zip'
    });

 return this.http.get(`${environment.apiUrl}${path}`, { 
   headers: headers, 
   search: params, 
   responseType: ResponseContentType.ArrayBuffer //magic
 })
          .catch(this.formatErrors)
          .map((res:Response) => res['_body']);
}

虽然这个问题很老了,但没有一个答案是可行的。 据我所知,所有的文件都是先加载到内存中,然后保存。 这样我们:

导致延迟,为此必须实现自定义加载。 将文件加载到内存中,这意味着对于大文件,浏览器将崩溃。 请勿使用已实现的浏览器下载功能。

前端端非常简单(Angular 12):

downloadFile(url: string, fileName: string): void {
   const downloadLink = document.createElement('a');
   downloadLink.download = fileName;
   downloadLink.href = url;
   downloadLink.click();
}

在后端(。NET 6)我们需要使用流并写入响应体:

public void Get(string fileId)
{
    var fileName = fileService.GetFileName(fileId);
    var fileContentType = fileService.GetFileContentType(fileId);
    this.Response.Headers.Add(HeaderNames.ContentType, fileContentType);
    this.Response.Headers.Add(HeaderNames.ContentDisposition, $"attachment; filename=\"{fileName}\"");
    fileService.GetFile(Response.Body, fileId);
}

文件内容类型和名称可以从DB(如果您将文件信息保存在其中)或文件系统中检索。 从扩展解析内容类型。

我像这样写入流:

public void GetFile(Stream writeStream, string fileId)
{
    var file = GetFileInfo(fileId);
    try
    {
        var fileStream = File.OpenRead(file.FullName);
        byte[] buffer = new byte[32768];
        int read;
        while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            writeStream.Write(buffer, 0, read);
        }
        writeStream.Flush();
    }
    catch (Exception e)
    {
        throw new CustomException($"Error occured while reading the file. Inner Exception Message: ({e.Message}) Stack Trace: ({e.StackTrace})", ErrorCode.FileReadFailure, e);
    }
}

请记住,为了表示目的,我简化了我的实现,所以还没有对其进行测试。

问题是可观察对象运行在另一个上下文中,所以当你尝试创建URL var时,你有一个空对象,而不是你想要的blob。

解决这个问题的众多方法之一如下:

this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),
                 error => console.log('Error downloading the file.'),
                 () => console.info('OK');

当请求准备好时,它将调用函数"downloadFile",定义如下:

downloadFile(data: Response) {
  const blob = new Blob([data], { type: 'text/csv' });
  const url= window.URL.createObjectURL(blob);
  window.open(url);
}

这个blob已经被完美地创建了,所以URL变量,如果没有打开新的窗口,请检查你已经导入'rxjs/Rx';

import 'rxjs/Rx' ;

我希望这能帮助到你。

更新Hector的答案使用文件保护程序和HttpClient的第2步:

public downloadFile(file: File): Observable<Blob> {
    return this.http.get(file.fullPath, {responseType: 'blob'})
}

我找到了一个从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文件格式。如果需要其他格式,请使用正确的扩展名更改介质类型和文件名。