簡體   English   中英

如何使用REST API中的angular下載文件?

[英]How to download file using angular from REST API?

我已經找到了來自不同博客和SO的以下代碼,因為我找不到執行此操作的任何教程。

我要做的是使用angular和typescript從REST API下載文件。 我沒有對api的訪問權限(僅具有類似“ http:// ...”的url,僅此而已。

這是我的打字稿代碼:

   //Downloading File
  // may be located in any component


  let options = {
    responseType: ResponseContentType.Blob //This has compilation error. Cannot recognize ResponseContentType.Blob
  }
  // pass options to request
  this.http.get(url, options)

let type = "my/mime";
// download the file - retrieve observable
this.http.get(url, options).map((res: Body) => new Blob([res.blob()], { type: type }));

public downloadAttachment(attachment: MediaDownloadFileDto): void {
  this.myDownloadService.downloadFile(downloadUrl, mimeType).subscribe((fileBlob: Blob) => {
      fileSaver.saveAs(fileBlob, attachment.filename);
  }, (message: string) => {
      // error handling...
  });
}

// may be located in any service:
public downloadFile(url: string, type: string): Observable<Blob> {
  let options = {
      responseType: ResponseContentType.Blob
  };
  return this.http.get(url, options).map((res: Body) => new Blob([res.blob()], { type: type }));
}

這是我正在使用的HTML按鈕:

<button class="nui-button nui-button--alt download" (click)="downloadFile(url,options)">Download Template</button>

謝謝

您可以簡單地使用HTML download屬性。

嘗試這個:

<a href="https://some-rest-api.com/some-file.mp4" download>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM