Skip to content

Angular HttpClient can't download files from the .Net Core API #30604

@TzuHuanTai

Description

@TzuHuanTai

🐞 bug report

Affected Package

HttpClient from @angular/common/http

Is this a regression?

No

Description

I'm using Angular 6 to download .docx files from the .Net Core 2.1 API.

The code of .Net Core below can directly get the .docx file through an URL in the browser after publishing to IIS.

This is the link I used to troubleshoot, so I don't think .Net Core is wrong:

https://stackoverflow.com/questions/42460198/return-file-in-asp-net-core-web-api

When I use HttpClient to call the API in Angular, the body will be empty in the response...

.Net Core Controller

[HttpGet("[action]")]
public IActionResult DemoWordGet(string Custom, string Variety, string Type,
    string Brand, string ProductName, string Company = "test",
    string BeginDate = "2019-5-21", string EndDate = "2019-5-22")
{
    string DemoFile = _hostingEnvironment.ContentRootPath + @"\Templates\demo.docx";
    byte[] byteArray = System.IO.File.ReadAllBytes(DemoFile);
    MemoryStream memoryStream = new MemoryStream();

    memoryStream.Write(byteArray, 0, byteArray.Length);

    WordprocessingDocument document = WordprocessingDocument.Open(memoryStream, true);

    Body body = document.MainDocumentPart.Document.Body;
			
    Paragraph paragraph = body.AppendChild(new Paragraph());

    DocumentFormat.OpenXml.Wordprocessing.Run run = paragraph.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
    run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("it is test context!"));
    document.Close();
			
    string FileName = "test-" + DateTime.Now.ToString("yyyyMMdd") + ".docx";
    memoryStream.Seek(0, SeekOrigin.Begin);

    return File(memoryStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", FileName);
}

Angular Component

this._printService.GetWord(printInfo).subscribe((response:any) => {
    const filename = response.headers.get('Content-Disposition').split(/[;'=]/).pop();
    saveAs(response.body, decodeURIComponent(filename));
});

Angular API PrintService

constructor(private http: HttpClient) { }

GetWord(params: HttpParams): Observable<any> {
    return this.http.get(
            `${this.apiUrl}/DemoWordGet`, 
            {   
                params,
                responseType: 'blob',
                observe: 'response',
            });
}

The request and response seems fine in the browser, however the body of response shows nothing in `HttpClient`

https://imgur.com/a/VA04qiE

I've tried sometning below:

  1. I enter the debug mode and discover that the response body will be empty until the subscription complete!!!

  2. The same problem is in Microsoft Edge as well.

  3. I can successfully download the file by using the code below:

async test() {
    let res = await fetch(`${this.apiUrl}/DemoWordGet`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/octet-stream',
        }
    });
    const filename = response.headers.get('Content-Disposition').split(/[;'=]/).pop();
    response.blob().then(x => {
        saveAs(x, decodeURIComponent(filename));
    });
}

Is this a bug about HttpClient??

I still have no idea what I'm doing wrong in Angular?

🌍 Your Environment

Angular Version:


Angular CLI: 6.0.8
Node: 9.10.1
OS: win32 x64
Angular: 6.0.6
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.6.8
@angular-devkit/build-angular      0.6.8
@angular-devkit/build-optimizer    0.6.8
@angular-devkit/core               0.6.8
@angular-devkit/schematics         0.6.8
@angular/cdk                       6.4.6
@angular/cli                       6.0.8
@angular/material                  6.4.6
@angular/material-moment-adapter   6.4.1
@schematics/angular                0.6.8
@schematics/update                 0.6.8
rxjs                               6.2.1
typescript                         2.7.2
webpack                            4.4.1

Anything else relevant?

Chrome: 74.0.3729.157

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions