作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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();
});
关于c# - Angular - 如何在 subscribe() 上从 Web API 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57326028/
我是一名优秀的程序员,十分优秀!