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

4
在Angular中,我正在尝试从我的Web API服务器下载Excel文件。
如果我像这样从组件调用我的API:
<a href="http://localhost:55820/api/download">Download</a>

文件下载很顺利,没有处理响应,我得到了期望的行为:

Success download

我该如何在我的 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;

提前感谢!:)

3个回答

2

try this work around:

.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();
}); 

1

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

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

这个很好用,但是生成的文件名不能被更改。我结合了这个解决方案,现在它完美地工作了。 - Iñigo

0

您可以添加支持所有浏览器的js-file-download库

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");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接