Angular无法从.Net Core API下载文件

时间:2019-05-21 03:18:40

标签: c# angular typescript .net-core filesaver.js

我正在使用 Angular 6 .Net Core 2.1 API下载.docx文件。

下面的.Net Core代码发布到IIS后,可以通过浏览器中的URL直接获取.docx文件。

这是我用来进行故障排除的链接,所以我认为.Net Core并没有错:
Return file in ASP.Net Core Web API

当我使用 HttpClient 在Angular中调用API时,响应中的正文将为空...

.Net核心控制器

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

角度组件

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

Angular API服务

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

请求和响应在浏览器中显示正常,但是console.log()中订阅的响应什么也没有显示...

https://imgur.com/a/VA04qiE

Chrome版本:74.0.3729.157

-----更新-----

  1. 我进入调试模式,发现响应主体将为空,直到订阅完成!

  2. Microsoft Edge中也存在相同的问题。

  3. 我可以使用以下代码成功下载文件:

async test() {
    let res = await fetch(`${this.apiUrl}/DemoWordGet`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/octet-stream',
        }
    });

    res.blob().then(x => {
        saveAs(x, 'test.docx');
    });
}

这是关于HttpClient的错误吗?

我仍然不知道我在Angular做错了什么?

2 个答案:

答案 0 :(得分:0)

您正在将blob转换为json,这是错误的,因此您的代码必须对此进行更改

productOf2Normals :: Double -> Double -> Rand Double
productOf2Normals mu sigma = do
  x1 <- normal mu sigma
  x2 <- normal mu sigma
  return $ x1 * x2

对此

responseType: 'blob' as 'json'

您应该使用createObjectUrl下载类似这样的文件

responseType: "blob"

答案 1 :(得分:0)

 return this.http
    .get(`${this.apiUrl}/DemoWordGet`, {
      responseType: ResponseContentType.Blob
    })
    .map(res => {
      return {
        filename: 'filename.pdf',
        data: res.blob()
      };
    });

这应该是将content-type设置为blob的方式