如何使用Angular2

时间:2016-02-01 19:15:37

标签: angular typescript download fileapi

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

请求没问题(适用于MVC,我们可以记录收到的数据)但我无法弄清楚如何保存下载的数据(我主要遵循与this post中相同的逻辑) 。我确信它很简单,但到目前为止我根本就没理解它。

组件功能的代码如下。我已经尝试了不同的替代方案,blob方式应该是我理解的方式,但createObjectURL中没有函数URL。我甚至无法在窗口中找到URL的定义,但显然它存在。如果我使用FileSaver.js module,我会得到同样的错误。所以我猜这是最近发生的变化或者尚未实施。如何在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);
}

28 个答案:

答案 0 :(得分:127)

问题是observable在另一个上下文中运行,所以当你尝试创建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 var,如果没有打开新窗口,请检查您是否已导入'rxjs / Rx';

  import 'rxjs/Rx' ;

我希望这可以帮到你。

答案 1 :(得分:72)

试试this

1 - 为show save / open file弹出窗口安装依赖项

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

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-在组件中使用&#39;文件保护程序&#39;

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

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

这对我有用!

答案 2 :(得分:36)

如果您不需要在请求中添加标题,要在Angular2中下载文件,您可以做一个简单的事情:

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

在你的组件中。

答案 3 :(得分:29)

这是为了让人们了解如何使用HttpClient和文件保护程序:

  1. 安装文件保护程序
  2.   

    npm install file-saver --save

         

    npm install @ types / file-saver --save

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

答案 4 :(得分:17)

Alejandro Corredor所述,这是一个简单的范围错误。 subscribe是异步运行的,open必须放在该上下文中,以便在我们触发下载时数据完成加载。

也就是说,有两种方法可以做到这一点。正如文档所建议的那样,服务负责获取和映射数据:

//On the service:
downloadfile(runname: string, type: string){
  var headers = new Headers();
  headers.append('responseType', 'arraybuffer');
  return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type)
            .map(res => new Blob([res],{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
            .catch(this.logAndPassOn);
}

然后,在组件上我们只订阅并处理映射数据。有两种可能性。 第一个,正如原帖中所建议的那样,但需要Al​​ejandro指出的小修正:

//On the component
downloadfile(type: string){
  this.pservice.downloadfile(this.rundata.name, type)
      .subscribe(data => window.open(window.URL.createObjectURL(data)),
                  error => console.log("Error downloading the file."),
                  () => console.log('Completed file download.'));
  }

第二种方式是使用FileReader。逻辑是相同的但我们可以明确地等待FileReader加载数据,避免嵌套,并解决异步问题。

//On the component using FileReader
downloadfile(type: string){
    var reader = new FileReader();
    this.pservice.downloadfile(this.rundata.name, type)
        .subscribe(res => reader.readAsDataURL(res), 
                    error => console.log("Error downloading the file."),
                    () => console.log('Completed file download.'));

    reader.onloadend = function (e) {
        window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no');
  }
}

注意:我正在尝试下载Excel文件,即使下载已触发(因此这回答了问题),该文件也已损坏。 See the answer to this post 避免损坏的文件。

答案 5 :(得分:16)

这个怎么样?

this.http.get(targetUrl,{responseType:ResponseContentType.Blob})
        .catch((err)=>{return [do yourself]})
        .subscribe((res:Response)=>{
          var a = document.createElement("a");
          a.href = URL.createObjectURL(res.blob());
          a.download = fileName;
          // start download
          a.click();
        })

我能用它做 不需要额外的包裹。

答案 6 :(得分:15)

下载角度为2.4.x的* .zip解决方案:您必须从'@ 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']);
}

答案 7 :(得分:9)

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

我认为最好有

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

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

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

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

答案 8 :(得分:9)

对于较新的角度版本:

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


import {saveAs} from 'file-saver/FileSaver';

this.http.get('endpoint/', {responseType: "blob", headers: {'Accept': 'application/pdf'}})
  .subscribe(blob => {
    saveAs(blob, 'download.pdf');
  });

答案 9 :(得分:5)

到目前为止,我发现答案缺乏洞察力和警告。您可以并且应该注意与IE10 +不兼容(如果您愿意的话)。

这是包含应用程序部分和服务部分的完整示例。请注意,我们设置了 observe:“ response” 来捕获文件名的标题。还要注意,Content-Disposition标头必须由服务器设置和公开,否则当前的Angular HttpClient将不会继续传递它。我在下面添加了 dotnet核心这段代码。

public exportAsExcelFile(dataId: InputData) {
    return this.http.get(this.apiUrl + `event/export/${event.id}`, {
        responseType: "blob",
        observe: "response"
    }).pipe(
        tap(response => {
            this.downloadFile(response.body, this.parseFilename(response.headers.get('Content-Disposition')));
        })
    );
}

private downloadFile(data: Blob, filename: string) {
    const blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8;'});
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
    } else {
        const link = document.createElement('a');
        if (link.download !== undefined) {
            // Browsers that support HTML5 download attribute
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

private parseFilename(contentDisposition): string {
    if (!contentDisposition) return null;
    let matches = /filename="(.*?)"/g.exec(contentDisposition);

    return matches && matches.length > 1 ? matches[1] : null;
}

Dotnet核心,具有Content-Disposition和MediaType

 private object ConvertFileResponse(ExcelOutputDto excelOutput)
    {
        if (excelOutput != null)
        {
            ContentDisposition contentDisposition = new ContentDisposition
            {
                FileName = excelOutput.FileName.Contains(_excelExportService.XlsxExtension) ? excelOutput.FileName : "TeamsiteExport.xlsx",
                Inline = false
            };
            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            Response.Headers.Add("Content-Disposition", contentDisposition.ToString());
            return File(excelOutput.ExcelSheet, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
        else
        {
            throw new UserFriendlyException("The excel output was empty due to no events.");
        }
    }

答案 10 :(得分:5)

对于使用Redux Pattern的人

我在文件保护程序中添加了@Hector Cuevas在他的回答中命名。使用Angular2 v.2.3.1,我不需要添加@ types / file-saver。

以下示例是将日记下载为PDF。

期刊行动

public static DOWNLOAD_JOURNALS = '[Journals] Download as PDF';
public downloadJournals(referenceId: string): Action {
 return {
   type: JournalActions.DOWNLOAD_JOURNALS,
   payload: { referenceId: referenceId }
 };
}

public static DOWNLOAD_JOURNALS_SUCCESS = '[Journals] Download as PDF Success';
public downloadJournalsSuccess(blob: Blob): Action {
 return {
   type: JournalActions.DOWNLOAD_JOURNALS_SUCCESS,
   payload: { blob: blob }
 };
}

期刊效果

@Effect() download$ = this.actions$
    .ofType(JournalActions.DOWNLOAD_JOURNALS)
    .switchMap(({payload}) =>
        this._journalApiService.downloadJournal(payload.referenceId)
        .map((blob) => this._actions.downloadJournalsSuccess(blob))
        .catch((err) => handleError(err, this._actions.downloadJournalsFail(err)))
    );

@Effect() downloadJournalSuccess$ = this.actions$
    .ofType(JournalActions.DOWNLOAD_JOURNALS_SUCCESS)
    .map(({payload}) => saveBlobAs(payload.blob, 'journal.pdf'))

期刊服务

public downloadJournal(referenceId: string): Observable<any> {
    const url = `${this._config.momentumApi}/api/journals/${referenceId}/download`;
    return this._http.getBlob(url);
}

HTTP服务

public getBlob = (url: string): Observable<any> => {
    return this.request({
        method: RequestMethod.Get,
        url: url,
        responseType: ResponseContentType.Blob
    });
};

期刊缩减器 虽然这只设置了我们应用程序中使用的正确状态,但我仍然希望将其添加到显示完整模式中。

case JournalActions.DOWNLOAD_JOURNALS: {
  return Object.assign({}, state, <IJournalState>{ downloading: true, hasValidationErrors: false, errors: [] });
}

case JournalActions.DOWNLOAD_JOURNALS_SUCCESS: {
  return Object.assign({}, state, <IJournalState>{ downloading: false, hasValidationErrors: false, errors: [] });
}

我希望这有用。

答案 11 :(得分:5)

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

服务&#39; pservice&#39; :

UIKeyboardTypeDecimalPad

组件部分:

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

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

答案 12 :(得分:4)

我正在使用Angular 4和4.3 httpClient对象。我修改了我在Js&#39;中找到的答案。创建链接对象的技术博客,使用它进行下载,然后销毁它。

客户端:

doDownload(id: number, contentType: string) {
    return this.http
        .get(this.downloadUrl + id.toString(), { headers: new HttpHeaders().append('Content-Type', contentType), responseType: 'blob', observe: 'body' })
}

downloadFile(id: number, contentType: string, filename:string)  {

    return this.doDownload(id, contentType).subscribe(  
        res => { 
            var url = window.URL.createObjectURL(res);
            var a = document.createElement('a');
            document.body.appendChild(a);
            a.setAttribute('style', 'display: none');
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
            a.remove(); // remove the element
        }, error => {
            console.log('download error:', JSON.stringify(error));
        }, () => {
            console.log('Completed file download.')
        }); 

} 

之前已将此.downloadUrl的值设置为指向api。我用它来下载附件,所以我知道id,contentType和文件名: 我使用MVC api返回文件:

 [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
    public FileContentResult GetAttachment(Int32 attachmentID)
    { 
        Attachment AT = filerep.GetAttachment(attachmentID);            
        if (AT != null)
        {
            return new FileContentResult(AT.FileBytes, AT.ContentType);  
        }
        else
        { 
            return null;
        } 
    } 

附件类如下所示:

 public class Attachment
{  
    public Int32 AttachmentID { get; set; }
    public string FileName { get; set; }
    public byte[] FileBytes { get; set; }
    public string ContentType { get; set; } 
}

filerep存储库从数据库返回文件。

希望这有助于某人:)

答案 13 :(得分:4)

要下载并显示 PDF 文件,剪切的代码非常相似,如下所示:

  private downloadFile(data: Response): void {
    let blob = new Blob([data.blob()], { type: "application/pdf" });
    let url = window.URL.createObjectURL(blob);
    window.open(url);
  }

  public showFile(fileEndpointPath: string): void {
    let reqOpt: RequestOptions = this.getAcmOptions();  //  getAcmOptions is our helper method. Change this line according to request headers you need.
    reqOpt.responseType = ResponseContentType.Blob;
    this.http
      .get(fileEndpointPath, reqOpt)
      .subscribe(
        data => this.downloadFile(data),
        error => alert("Error downloading file!"),
        () => console.log("OK!")
      );
  }

答案 14 :(得分:3)

以下代码对我有用

let link = document.createElement('a');
link.href = data.fileurl; //data is object received as response
link.download = data.fileurl.substr(data.fileurl.lastIndexOf('/') + 1);
link.click();

答案 15 :(得分:3)

使用文件保护程序和HttpClient更新Hector的答案,进行步骤2:

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

答案 16 :(得分:3)

这是我做的事-

// service method
downloadFiles(vendorName, fileName) {
    return this.http.get(this.appconstants.filesDownloadUrl, { params: { vendorName: vendorName, fileName: fileName }, responseType: 'arraybuffer' }).map((res: ArrayBuffer) => { return res; })
        .catch((error: any) => _throw('Server error: ' + error));
}

// a controller function which actually downloads the file
saveData(data, fileName) {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    let blob = new Blob([data], { type: "octet/stream" }),
        url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
}

// a controller function to be called on requesting a download
downloadFiles() {
    this.service.downloadFiles(this.vendorName, this.fileName).subscribe(data => this.saveData(data, this.fileName), error => console.log("Error downloading the file."),
        () => console.info("OK"));
}

该解决方案引用自- here

答案 17 :(得分:2)

我有一个解决方案,从角度2下载而不会腐败, 使用spring mvc和angular 2

1st-我的返回类型是: - java端的 ResponseEntity 。这里我发送byte []数组有来自控制器的返回类型。

第2步 - 将文件管理器包含在工作区中 - 在索引页面中:

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

第3代 - 在组件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文件格式。如果您想要其他格式,请使用正确的扩展名更改mediatype和文件名。

答案 18 :(得分:2)

如果您尝试在自己的subscribe

中调用新方法会更好。
this._reportService.getReport()
    .subscribe((data: any) => {
        this.downloadFile(data);
    },
        (error: any) => onsole.log(error),
        () => console.log('Complete')
    );

downloadFile(data)函数内部,我们需要制作block, link, href and file name

downloadFile(data: any, type: number, name: string) {
    const blob = new Blob([data], {type: 'text/csv'});
    const dataURL = window.URL.createObjectURL(blob);

    // IE doesn't allow using a blob object directly as link href
    // instead it is necessary to use msSaveOrOpenBlob
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob);
      return;
    }

    const link = document.createElement('a');
    link.href = dataURL;
    link.download = 'export file.csv';
    link.click();

    setTimeout(() => {

      // For Firefox it is necessary to delay revoking the ObjectURL
      window.URL.revokeObjectURL(dataURL);
      }, 100);
    }
}

答案 19 :(得分:1)

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

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

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

答案 20 :(得分:0)

只需将url设置为href,如下所示。

<a href="my_url">Download File</a>

答案 21 :(得分:0)

<a href="my_url" download="myfilename">Download file</a>

my_url应该具有相同的来源,否则它将重定向到该位置

答案 22 :(得分:0)

我今天也面临着同样的情况,我必须下载一个PDF文件作为附件(该文件不应在浏览器中呈现,而应下载)。为了实现这一点,我发现必须将文件放在Angular Blob中,并同时在响应中添加Content-Disposition标头。

这是我能获得的最简单的方法(角度7):

服务内部:

getFile(id: String): Observable<HttpResponse<Blob>> {
  return this.http.get(`./file/${id}`, {responseType: 'blob', observe: 'response'});
}

然后,当我需要在组件中下载文件时,我可以简单地进行操作:

fileService.getFile('123').subscribe((file: HttpResponse<Blob>) => window.location.href = file.url);

更新:

从服务中删除了不必要的标头设置

答案 23 :(得分:0)

如果仅将参数发送到URL,则可以通过以下方式进行操作:

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

在接收参数的服务中

答案 24 :(得分:0)

This的答案表明,出于安全原因,您不能直接使用AJAX下载文件。所以我将描述在这种情况下我该怎么做,

01。。在href文件内的锚标记中添加component.html属性,
例如:-

<div>
       <a [href]="fileUrl" mat-raised-button (click)='getGenaratedLetterTemplate(element)'> GENARATE </a>
</div>

02。。请执行component.ts中的所有以下步骤以绕过安全级别并打开“另存为”弹出对话框,
例如:-

import { environment } from 'environments/environment';
import { DomSanitizer } from '@angular/platform-browser';
export class ViewHrApprovalComponent implements OnInit {
private apiUrl = environment.apiUrl;
  fileUrl
 constructor(
    private sanitizer: DomSanitizer,
    private letterService: LetterService) {}
getGenaratedLetterTemplate(letter) {

    this.data.getGenaratedLetterTemplate(letter.letterId).subscribe(
      // cannot download files directly with AJAX, primarily for security reasons);
    console.log(this.apiUrl + 'getGeneratedLetter/' + letter.letterId);
    this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.apiUrl + 'getGeneratedLetter/' + letter.letterId);
  }
  

注意:如果收到状态代码为200的错误“确定”,此答案将起作用

答案 25 :(得分:0)

好吧,我写了一段代码,受到上述许多答案的启发,这些代码在服务器发送带有内容处置标头的文件的情况下很容易用,而除了rxjs和angular之外,该服务器没有任何第三方安装。 / p>

首先,如何从组件文件中调用代码

this.httpclient.get(
   `${myBackend}`,
   {
      observe: 'response',
      responseType: 'blob'
   }
).pipe(first())
.subscribe(response => SaveFileResponse(response, 'Custom File Name.extension'));

如您所见,基本上是来自angular的平均后端调用,但有两个变化

  1. 我观察的是反应,而不是身体
  2. 我明确表示响应是一滴污垢

从服务器上获取文件后,原则上,我将将文件保存到助手功能的整个任务委托给我,该功能保存在一个单独的文件中,然后导入需要的任何组件中

export const SaveFileResponse = 
(response: HttpResponse<Blob>, 
 filename: string = null) => 
{
    //null-checks, just because :P
    if (response == null || response.body == null)
        return;

    let serverProvidesName: boolean = true;
    if (filename != null)
        serverProvidesName = false;

    //assuming the header is something like
    //content-disposition: attachment; filename=TestDownload.xlsx; filename*=UTF-8''TestDownload.xlsx
    if (serverProvidesName)
        try {
            let f: string = response.headers.get('content-disposition').split(';')[1];
            if (f.includes('filename='))
                filename = f.substring(10);
        }
        catch { }
    SaveFile(response.body, filename);
}

//Create an anchor element, attach file to it, and
//programmatically click it. 
export const SaveFile = (blobfile: Blob, filename: string = null) => {
    const a = document.createElement('a');
    a.href = window.URL.createObjectURL(blobfile);
    a.download = filename;
    a.click();
}

那里,不再有神秘的GUID文件名!我们可以使用服务器提供的任何名称,而不必在客户端中显式指定它,也可以覆盖服务器提供的文件名(如本例所示)。 此外,如果需要,可以轻松地更改从内容处置中提取文件名的算法以适应他们的需求,而其他所有内容都不会受到影响-如果在提取过程中出现错误,它只会传递“ null”作为文件名。

正如已经指出的另一个答案一样,IE一如既往需要特殊处理。但是随着铬的出现,几个月后,我就不必为开发新应用而担心。 还存在撤销URL的问题,但是我对此不太确定,因此,如果有人可以在评论中提供帮助,那将很棒。

答案 26 :(得分:0)

如果Http请求失败,这些可观察对象将发出错误。

npm install @angular/http@latest

//在服务文件中

  import { Http } from ''@angular/http;

文件保存模块 FileSaver.js用于在客户端保存文件,非常适合在客户端生成文件的Web应用程序。如果文件来自服务器,则应使用Content-Diposition附件响应标头,因为它具有更好的跨浏览器兼容性。 文件保存模块的缺点: RAM的大小 最大Blob大小限制 –>因此,我们可以使用替代方法,它是StreamSaver.js。 安装:

  npm install file-saver --save

//用于打字稿

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

处理示例项目 以下是有关在Angular中下载excel文件的示例项目。 我们可以找到其他下载文件的方式。而现在,这是第一种方法。 以下是服务文件。 // File.service.ts

import { Injectable } from '@angular/core';
import { Http, ResponseContentType, RequestOptions } from '@angular/http';
@Injectable({
    provideIn: 'root'
})
export class FileService {
    public url = '...';
    constructor(private http: Http) {
        // nothing to do
    }
    download() {
        const options = new RequestOptions({
            responseType: ResponseContentType.Blob
        });
        return this.http.get(url, options);
    }
}

how to download file in angular

答案 27 :(得分:0)

 let headers = new Headers({
                'Content-Type': 'application/json',
                'MyApp-Application': 'AppName',
                'Accept': 'application/vnd.ms-excel'
            });
            let options = new RequestOptions({
                headers: headers,
                responseType: ResponseContentType.Blob
            });


this.http.post(this.urlName + '/services/exportNewUpc', localStorageValue, options)
                .subscribe(data => {
                    if (navigator.appVersion.toString().indexOf('.NET') > 0)
                    window.navigator.msSaveBlob(data.blob(), "Export_NewUPC-Items_" + this.selectedcategory + "_" + this.retailname +"_Report_"+this.myDate+".xlsx");

                    else {
                        var a = document.createElement("a");
                        a.href = URL.createObjectURL(data.blob());
                        a.download = "Export_NewUPC-Items_" + this.selectedcategory + "_" + this.retailname +"_Report_"+this.myDate+ ".xlsx";
                        a.click();
                    }
                    this.ui_loader = false;
                    this.selectedexport = 0;
                }, error => {
                    console.log(error.json());
                    this.ui_loader = false;
                    document.getElementById("exceptionerror").click();
                });
相关问题