簡體   English   中英

以角度從 ASP.NET CORE api 下載 Content-Disposition

[英]Download Content-Disposition from ASP.NET CORE api in angular

如何以角度下載 foo.txt 我有一個 asp.net 核心后端,我在其中返回一個 foo.txt 文件。 字符串文件暫時沒有被使用。

這是我的后端

// GET api/download/contractAttachment
[HttpGet("download/{file}")]
public IActionResult GetFileAsync(string file)
{
    return File(Encoding.ASCII.GetBytes("foo"), "text/plain", "foo.txt");
}

這是我的角度前端

  download(file: string) {

    this.contractAttachementsService.downloadFile().subscribe(blob => {
        //I am not entering here how can I downloadFile here
    }, error => {
      console.log(error)
    });
  }

正如您在郵遞員中看到的那樣,我可以看到該文件,但是如何以角度下載它。 謝謝您的幫助

標頭

因為我在 Angular 代碼段中的訂閱中看到了一個 blob,所以您可以執行以下操作:

 download(file: string) {
    this.contractAttachementsService.downloadFile().subscribe((res)=> {
    // response to blob
    const blob = new Blob([res], {
    // Define the blob coversion type such as an xl file in my case
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    // in the case of a text file you can probably use built-in method
    // blob.text():
    // read here:https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
    })
    // Sanitizing the DOM against  XSS attacks (Cross Sit Scripting injections) and assign the sanitized object url to the fileUrl property
    this.fileToBeDownloaded = this.sanitizer.bypassSecurityTrustResourceUrl(
      // create a an object url from the response sanitized blob
      window.URL.createObjectURL(blob)
    )

    }, error => {
      console.log(error)
    });
  }

您需要聲明一個屬性來保存要下載的文件,並從'@angular/platform-browser' ​​rowser”注入DOMSanitizer

然后,在您的模板中,您應該有一個下載文件的操作。 您可以在ts部分使用綁定到fileTobDownloaded屬性的屬性綁定,如下所示:

 <a [href]="fileToBeDownloaded" download="fileName.txt">Download</a>

希望這對您的項目有所幫助

暫無
暫無

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

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