Angular - 如何在 subscribe() 上从 Web API 下载文件

Angular - How to download file from Web API on subscribe()

In Angular I'm trying to download an excel file from my Web API Server

如果我像这样从 <a> 组件调用 API:

<a href="http://localhost:55820/api/download">Download</a>

文件下载正常,没有处理响应我得到了想要的行为:

如何从我的 Angular DownloadService 发出请求并在 .subscribe() 处理结果?

this.downloadService.download()
      .subscribe(file => {/*What to put here for file downloading as above*/});

请注意,服务器会像这样创建响应:

byte[] b = File.ReadAllBytes(HttpRuntime.AppDomainAppPath + "/files/" + "file.xlsx");
var dataStream = new MemoryStream(b);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(dataStream);
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "File";
response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping("file.xlsx"));
return response;

提前致谢! :)

试试这个解决方法:

.subscribe(file => 
{  
   const a = document.createElement('a');
   a.setAttribute('type', 'hidden');  
   a.href = URL.createObjectURL(file.data);  
   a.download = fileName + '.xlsx';  
   a.click(); 
   a.remove();
}); 

上面的评论应该有效,但这里有另一种方法

.subscribe(file) {
  const blob = new Blob([file], { type: 'text/csv' }); // you can change the type
  const url= window.URL.createObjectURL(blob);
  window.open(url);
}

您可以添加支持所有浏览器的js文件下载库

npm install js-file-download --save

可以使用window.URL.createObjectURL(blob);但是IE不支持...

这是我从后端下载 Excel 文件的代码

import axios from 'axios';
import * as FileSaver from 'file-saver';

const result: any = await axios.create().post("http://localhost:8080/file",
{
   responseType: "arraybuffer",
});

let blob = new Blob([result.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
FileSaver.saveAs(blob, "export.xlsx");